Search code examples
dockerdockerfiledocker-machine

docker host port and container port


I am running a database container. I know to inspect port mappings, I can use command docker port <container_id or name>. So, I tried that command:

$docker port ea72b2c4ba47
3306/tcp -> 127.0.0.1:3666

I see the output, but which one means the port used by host machine and which one is the port of container?


Solution

  • 3306/tcp -> 127.0.0.1:3666 means port 3306 inside container is exposed on to port 3666 of host.

    More info here.

    If you think output of docker port command is confusing then use docker inspect command to retrieve port mapping. As mentioned here in official doc.

    docker ps docker port docker inspect are useful commands to get the info about port mapping.

    [user@jumphost ~]$ docker run -itd -p 3666:3306 alpine sh
    Unable to find image 'alpine:latest' locally
    latest: Pulling from library/alpine
    050382585609: Pull complete 
    Digest: sha256:6a92cd1fcdc8d8cdec60f33dda4db2cb1fcdcacf3410a8e05b3741f44a9b5998
    Status: Downloaded newer image for alpine:latest
    428c80bfca4e60e474f82fc5fe9c1c0963ff2a2f878a70799dc5da5cb232f27a
    [user@jumphost ~]$ docker ps
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
    428c80bfca4e        alpine              "sh"                3 seconds ago       Up 3 seconds        0.0.0.0:3666->3306/tcp   fervent_poitras
    [user@jumphost ~]$ docker port 428c80bfca4e
    3306/tcp -> 0.0.0.0:3666
    [user@jumphost ~]$ docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' 428c80bfca4e
     3306/tcp -> 3666 
    [user@jumphost ~]$
    

    docker inspect comtainer-id also gives a clear mapping of the ports.

    $ docker inspect 428c80bfca4e
         |
         |
    "Ports": {
                    "3306/tcp": [
                        {
                            "HostIp": "0.0.0.0",
                            "HostPort": "3666"
                        }
                    ]
                },
         |
         |
    

    Hope this helps.