What does localhost means inside a Docker container?

From inside a container, localhost always refers to the current container. It never refers to another container, and it never refers to anything else running on your physical system that’s not in the same container. It’s not usually useful to make outbound connections to localhost or configure localhost as your database host.

From a shell on your host system, localhost could refer to daemons running on your system outside Docker, or to ports you’ve published with docker run -p options.

From a different system, localhost refers to the system it’s called from.

In terms of IP addresses, localhost is always 127.0.0.1, and that IP address is special and is always localhost and behaves the same way as above.


If you want to make a connection to a container…

…from another container, the best way is to make sure they’re on the same Docker network (you started them from the same Docker Compose YAML file; you did a docker network create and then did docker run --net ... on the same network) and use Docker’s internal DNS service to refer to them by the container’s --name or its name in the Docker Compose YAML file and the port number inside the container. Even if the target has a published port with a docker run -p option or Docker Compose ports: setting, use the second (container-internal) port number.

…from outside Docker space, make sure you started the container with a docker run -p or Docker Compose ports: option, and connect to the host’s IP address or DNS name using the first port number from that option.

…from a terminal window or browser on the same physical host, not in a container, in this case and in this case only, localhost will work consistently.


Except:

If you started a container with --net host, localhost refers to the physical host, and you’re in the “terminal window on the same physical host” scenario.

If you’ve gone out of your way to have multiple servers in the same container, you can use localhost to communicate between them.

If you’re running in Kubernetes, and you have multiple containers in the same pod, you can use localhost to communicate between them. Between pods, you should set up a service in front of each pod/deployment, and use DNS names of the form service-name.namespace-name.svc.cluster.local.

Leave a Comment