Docker Containers
Accessing Container Ports
Containers run on our host machine, but are isolated from it by default. This means that services running inside containers are not accessible from the host machine or other machines on the network unless we explicitly expose and publish the necessary ports.
When you run a container, you can publish its port(s) using the -p (or --publish) flag. This flag maps a port on the host machine to a port inside the container - this means that any traffic arriving at the specified host port will be forwarded to the specified container port.
By default, published ports are bound on all host interfaces (effectively 0.0.0.0 for IPv4, and, depending on your setup, possibly :: for IPv6). If you want to expose the port only on a specific host interface, provide a host IP in the publish specification:
# Publish on localhost only (not reachable from other machines)
docker run -d -p 127.0.0.1:80:80 --name nginx_local_only nginx
# Publish on a specific host interface IP (replace with your host's IP on that interface)
docker run -d -p 192.168.1.10:80:80 --name nginx_lan_only nginx
The full --publish syntax is: --publish [HOST_IP:]HOST_PORT:CONTAINER_PORT[/PROTOCOL].
For example, to publish port 80 on the host and forward traffic to port 80 inside an NGINX container, you can use docker run -p 80:80 nginx. This forwards traffic arriving on port 80 of the host to port 80 inside the container.
For port publishing to work correctly, the following conditions must be met:
- The application running inside the container must be listening on the target port (NGINX, like most web servers, listens on port 80 by default).
- The host port you are trying to bind must not already be in use by another process on the host.
We haven't covered Dockerfiles yet, but usually the exposed ports are declared in the Dockerfile of the image using the EXPOSE instruction (a purely informational instruction that provides useful information about the ports the container is expected to listen on). The NGINX image declares port 80 as exposed. You can see an example of this by inspecting the NGINX image:
docker image inspect nginx --format '{{.Config.ExposedPorts}}'
Let's make a simple test:
# Publish on all interfaces
docker run -d -p 80:80 --name nginx_single_port nginx
# You should see port 80/tcp exposed and mapped to port 80 on the localhost
curl http://localhost:80
# or other interfaces
curl http://$(Painless Docker - 2nd Edition
A Comprehensive Guide to Mastering Docker and its EcosystemEnroll now to unlock all content and receive all future updates for free.
Hurry! This limited time offer ends in:
To redeem this offer, copy the coupon code below and apply it at checkout:
