Getting the name of the container from within the container

一笑奈何 提交于 2019-12-18 07:17:54

问题


I would like to get the docker container name from within a container. I need this information because I am running a script from the Dockerfile as an ENTRYPOINT that needs to know the node number. I am using the --scale with docker-compose to create a cluster of my image. I am able to get the hostname of the container which is the container ID. But is there a way to get the container name from inside the container?


回答1:


Docker remote apis should work for you.

Depending on the version of your docker used appropriate version of remote api. Check this for more info.

I made use of container-inspect api to retrieve the container name.

Follow these steps:

  • Figure out on which port docker daemon is listening. In my case it was 2375 which is the default port.
$ netstat -anp | grep dockerd
tcp        0      0 :::2375                 :::*                    LISTEN      7/dockerd
tcp        0      0 ::ffff:172.18.0.110:2375 ::ffff:172.18.0.1:29445 ESTABLISHED 7/dockerd
unix  2      [ ACC ]     STREAM     LISTENING     1242188041 7/dockerd           /var/run/docker/metrics.sock
unix  2      [ ACC ]     STREAM     LISTENING     1242187193 7/dockerd           /var/run/docker.sock
unix  2      [ ACC ]     STREAM     LISTENING     1242186375 7/dockerd           /var/run/docker/libnetwork/79ba9bb412445c757dd4cc2fc30c1cbc7efde8482bdc4c1cf15c4ce0e4190752.sock
unix  3      [ ]         STREAM     CONNECTED     1242187211 7/dockerd
unix  3      [ ]         STREAM     CONNECTED     1242183625 7/dockerd
unix  3      [ ]         STREAM     CONNECTED     1242184185 7/dockerd
  • Run a container and retrieve the container name.
$ docker run -it alpine sh
/ # apk update
/ # apk add curl
/ # apk add jq
/ # curl -s 192.168.0.37:2375/containers/$HOSTNAME/json | jq -r ".Name"
/zen_wescoff

NOTE: Here 192.168.0.37 is the ip of my machine. Also apart from container name you can retrieve lot of information using these docker remote apis.

Sample full output of container-inspect api

/ # curl -s 192.168.0.37:2375/containers/$HOSTNAME/json?pretty=true
{
    "Id": "3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9",
    "Created": "2019-06-20T09:09:51.258807808Z",
    "Path": "sh",
    "Args": [],
    "State": {
        "Status": "running",
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 3824,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2019-06-20T09:09:53.341188978Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "sha256:4d90542f0623c71f1f9c11be3da23167174ac9d93731cf91912922e916bab02c",
    "ResolvConfPath": "/var/lib/docker/containers/3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9/hostname",
    "HostsPath": "/var/lib/docker/containers/3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9/hosts",
    "LogPath": "/var/lib/docker/containers/3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9/3409974f45bedacd3adbe663679e4eb7a74006483e3a3b04985e5a7cc65229b9-json.log",
    "Name": "/jovial_moser",
    "RestartCount": 0,
    "Driver": "overlay2",
    "Platform": "linux",
    "MountLabel": "",
    "ProcessLabel": "",
    "AppArmorProfile": "docker-default",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "NetworkMode": "default",
        "PortBindings": {},
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "AutoRemove": false,
        "VolumeDriver": "",
        "VolumesFrom": null,
        "CapAdd": null,
        "CapDrop": null,
        "Capabilities": null,
        "Dns": [],
        "DnsOptions": [],
        "DnsSearch": [],
        "ExtraHosts": null,
        "GroupAdd": null,
        "IpcMode": "private",
        "Cgroup": "",
        "Links": null,
        "OomScoreAdj": 0,
        "PidMode": "",
        "Privileged": false,
        "PublishAllPorts": false,
        "ReadonlyRootfs": false,
        "SecurityOpt": null,
        "UTSMode": "",
        "UsernsMode": "",
        "ShmSize": 67108864,
        "Runtime": "runc",
        "ConsoleSize": [0, 0],
        "Isolation": "",
        "CpuShares": 0,
        "Memory": 0,
        "NanoCpus": 0,
        "CgroupParent": "",
        "BlkioWeight": 0,
        "BlkioWeightDevice": [],
        "BlkioDeviceReadBps": null,
        "BlkioDeviceWriteBps": null,
        "BlkioDeviceReadIOps": null,
        "BlkioDeviceWriteIOps": null,
        "CpuPeriod": 0,
        "CpuQuota": 0,
        "CpuRealtimePeriod": 0,
        "CpuRealtimeRuntime": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "Devices": [],
        "DeviceCgroupRules": null,
        "DeviceRequests": null,
        "DiskQuota": 0,
        "KernelMemory": 0,
        "KernelMemoryTCP": 0,
        "MemoryReservation": 0,
        "MemorySwap": 0,
        "MemorySwappiness": null,
        "OomKillDisable": false,
        "PidsLimit": null,
        "Ulimits": null,
        "CpuCount": 0,
        "CpuPercent": 0,
        "IOMaximumIOps": 0,
        "IOMaximumBandwidth": 0,
        "MaskedPaths": ["/proc/asound", "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/proc/scsi", "/sys/firmware"],
        "ReadonlyPaths": ["/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger"]
    },
    "GraphDriver": {
        "Data": {
            "LowerDir": "/var/lib/docker/overlay2/a5f16849169cb7c773f4d204089f8e53daf5b648864846ee1d1f076cef9f8a39-init/diff:/var/lib/docker/overlay2/edb63c15d70f0a29c60f3725ed952dd76439bef4da8915e66ffe6ed1ecf02107/diff",
            "MergedDir": "/var/lib/docker/overlay2/a5f16849169cb7c773f4d204089f8e53daf5b648864846ee1d1f076cef9f8a39/merged",
            "UpperDir": "/var/lib/docker/overlay2/a5f16849169cb7c773f4d204089f8e53daf5b648864846ee1d1f076cef9f8a39/diff",
            "WorkDir": "/var/lib/docker/overlay2/a5f16849169cb7c773f4d204089f8e53daf5b648864846ee1d1f076cef9f8a39/work"
        },
        "Name": "overlay2"
    },
    "Mounts": [],
    "Config": {
        "Hostname": "3409974f45be",
        "Domainname": "",
        "User": "",
        "AttachStdin": true,
        "AttachStdout": true,
        "AttachStderr": true,
        "Tty": true,
        "OpenStdin": true,
        "StdinOnce": true,
        "Env": ["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],
        "Cmd": ["sh"],
        "Image": "alpine",
        "Volumes": null,
        "WorkingDir": "",
        "Entrypoint": null,
        "OnBuild": null,
        "Labels": {}
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "7f41a5043e99bb110e215ac8e13a8a2c37838b25c6a9fa985584ff458c1e52cc",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/7f41a5043e99",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "7aa9f269772edff8a9b7f895d51d6dd472a5820ff56a643134465ab8bff1914e",
        "Gateway": "172.17.0.1",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "172.17.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "MacAddress": "02:42:ac:11:00:02",
        "Networks": {
            "bridge": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": null,
                "NetworkID": "55987078c24843c830172de5c352b00c96cb3f177a349437dd7bee9bd1814e86",
                "EndpointID": "7aa9f269772edff8a9b7f895d51d6dd472a5820ff56a643134465ab8bff1914e",
                "Gateway": "172.17.0.1",
                "IPAddress": "172.17.0.2",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:11:00:02",
                "DriverOpts": null
            }
        }
    }
}

So in-short you need to know ip for your machine and the port on which docker daemon is listening to retrieve any sort of information from within the container.

Hope this helps, let me know.



来源:https://stackoverflow.com/questions/56675083/getting-the-name-of-the-container-from-within-the-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!