Linux Labs

Containers: Docker and compose / Stage 2 of 11

Ports, variables and restart

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 8 · on a machine · 7 min

Container port and server port

A container has its own network with its own ports. This step covers how to open its port on the server.

Docker gives a container its own network namespace: its own interfaces, its own address in Docker's internal network and its own ports. nginx in site listens on port 80 inside the container. The server's interfaces have no such port, and nothing listens on port 8080 of the server, hence the refusal. 80/tcp in the PORTS column is the port the image declared; by itself it opens nothing on the server.

For the server to accept connections and pass them into the container, the port is published. Port publishing is the -p server_port:container_port option of docker run:

bash
# server port 5000 → container port 3000
sudo docker run -d --name api -p 5000:3000 <image>

Docker passes connections on server port 5000 to container port 3000, and PORTS shows 0.0.0.0:5000->3000/tcp. The server port is held by the docker-proxy process, which sudo ss -tlnp shows. docker port <name> lists a container's published ports.

Ports are set when a container is created. To add a port, the container is re-created: docker rm -f removes it even while it runs, then docker run with the right -p.

Note

Port 80 of this machine is taken by the server's own nginx: curl http://localhost/ gets its answer, with the Server: nginx/1.24.0 (Ubuntu) header. Publishing -p 80:… fails with address already in use.

Exercise · do it

Open the site on a server port

Make the site from the site container open at http://localhost:8080/. Keep the container name and the image.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Open the site on port 8080 of the server not done yet
  • Keep site on the nginx:alpine image not done yet

Step goals

0 of 2
  • Open the site on port 8080 of the server — not done yet
  • Keep site on the nginx:alpine image — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Open the site on port 8080 of the server — not done yet
  • Keep site on the nginx:alpine image — not done yet
Loading…