Ports

A container's ports are private until you publish them

a browseron another machineHost: server-07, address 10.0.0.7nginx container172.17.0.2, listens on port 80by default: reachable only from this host8080host portdocker run -d -p 8080:80 nginx-p host port : container port10.0.0.7:8080forwarded to port 80A container's ports are private until you publish them on the host.The container has a network namespace of its own, so its port 80 is not the host's port 80.Publishing maps a port on the host to a port in the container. Two containers can both listenon 80 inside, as long as each is published on a different host port.

-p 8080:80 maps a host port to a container port.

Ports · Going deeper · 1 of 2

Lab: run a server and reach it

TypeLook fordocker run -d --name web -p 8080:80 nginxcurl -s localhost:8080 | head -4docker logs webdocker exec -it web shdocker rm -f weba long idthe start of the "Welcome to nginx" pagea line for the request you just madea shell inside the container; type exit to leavethe container is gone; curl now failsLab: run a web server and reach it through a published port."docker ps" lists running containers and shows the mapping as 0.0.0.0:8080->80/tcp.Try a second container on -p 8081:80. Both listen on 80 inside without any clash.

Run it, call it, read its logs, step inside, remove it.

Publishing ports · Going deeper · 2 of 2

Six ways to write a published port, and who can reach each

You writeDocker opens on the hostWho can connect-p 8080:80port 8080 on every network interfaceany machine that can reach the host-p 127.0.0.1:8080:80port 8080 on the loopback address onlyprograms on this host only-p 80a free high port that Docker pickslook it up: docker port web-p 5353:53/udpUDP port 5353 (TCP is the default)any machine that can reach the host-Pa free high port for each EXPOSE linelook them up: docker port webEXPOSE 80, and no -pnothingnobody outside: EXPOSE only documentsA second container asks for a host port that is taken (typical output, shortened)$ docker run -d -p 8080:80 nginxdocker: Error response from daemon: ... Bind for 0.0.0.0:8080 failed: port is already allocated.The short form -p 8080:80 listens on every interface. Add 127.0.0.1 to keep a port for this machine alone.Docker writes its own firewall rules for a published port, and they are consulted before rules made with ufw. So do notcount on ufw to hide a published port: bind it to 127.0.0.1, or do not publish it at all.

-p 8080:80 opens every interface. 127.0.0.1:8080:80 opens this machine only.

Volumes

What a container writes dies with it, unless it is in a volume

No volumeA volumepostgres:16.3data in its writable layerdocker rmData lostthe layer went with itpostgres:16.3the first containervolume pgdata, at /var/lib/postgresql/datareplacedpostgres:16.4a new container, same dataAnything a container writes dies with it, unless it is written to a volume.A volume is a directory that lives on the host, outside any container, and is mounted in at a path.Containers are meant to be replaced, not repaired, so every upgrade is a new container. Keepdatabases, uploads and anything else worth keeping in a volume.

The writable layer is temporary. A volume outlives the container.

Kinds of mount · Going deeper

Named volume, bind mount, tmpfs: what each keeps and hides

Named volumeBind mounttmpfs mountWritten as-v pgdata:/var/lib/postgresql/data-v /srv/conf:/etc/nginx/conf.d:ro--tmpfs /tmpThe data livesin /var/lib/docker/volumes/pgdataat the host path you namein memory onlyAfter docker rmkept, until docker volume rmkept: it is the host's own directorygoneStarts withthe image's files at that path, if newthe host's files: the image's are hiddennothingSource missingthe volume is createdan empty host directory is creatednot applicableUse it fordatabases, uploadscode while developing, config filesscratch files, secretsA named volume is Docker's to manage. A bind mount is a window onto the host. Each surprises in its own way.A new, empty named volume is first filled with whatever the image holds at that path. A bind mount does the opposite: itcovers the image's files with the host's. With -v, a mistyped host path is silently created as an empty directory and thecontainer starts without its data. The longer form, --mount type=bind,source=...,target=..., refuses a path that does not exist.

A named volume is filled from the image. A bind mount hides it.

Environment

One image runs everywhere; the settings come from outside

acme/web:1.4one image, built oncedeva container-e DB_HOST=localhost -e LOG_LEVEL=debugstaginga container-e DB_HOST=db.staging.internalproductiona container-e DB_HOST=db.prod.internalSettings come from outside the image, so one image runs everywhere.Environment variables are set when a container starts, and the program reads them. The imagethat passed its tests in staging is the very one that runs in production; only the settings differ.Never build passwords into an image: everyone who can pull it can read them.

Build once. Configure each container with environment variables.

Networks

On a shared network, containers find each other by name

One hostnetwork "shop"webnginx, port 80dbpostgres, port 5432db:54328080publishedvolume pgdatadb publishes no port:the outside world cannot reach itOn a shared network, containers find each other by name.Docker runs a small name service for each network you create. The web container asks for "db"and gets the database container's current address, whatever it is today. Publish only the portsthat outsiders need. Here that is the web server; the database stays private.

web calls db by name. Only web is published.

Compose

Compose writes the whole picture down in one file

services: web: image: nginx ports: ["8080:80"] environment: DB_HOST: db depends_on: [db] db: image: postgres:16 environment: { POSTGRES_PASSWORD: example } volumes: ["pgdata:/var/lib/postgresql/data"]volumes: pgdata:each service becomes a containerhost port 8080 to container port 80the service name works as a hostnamestart db before webkeep the data in the named volumethe volume, created once and then keptCompose writes the whole picture down in one file: docker compose up.The file from the last slide, as text. Compose creates the network, the volume and bothcontainers in order. The file goes into Git, so everyone on the team starts the same system.

One file, one command: docker compose up.

Compose · Going deeper · 1 of 2

Lab: two containers from one file

TypeLook fordocker compose up -ddocker compose psdocker compose exec web getent hosts dbdocker compose downdocker volume lsa network, a volume and two containers createdweb and db, both runningan address: the name db resolvescontainers and network removed, volume kepta volume whose name ends in pgdataLab: start two containers from one file.Save the file from the previous page as compose.yaml in an empty folder and run the commands there."docker compose down -v" also deletes the volume, and the data with it.

Up, look, resolve db by name, down. The volume stays.

Start order · Going deeper · 2 of 2

depends_on waits for started, not for ready, unless a health check says so

services: web: image: acme/web:1.4 restart: unless-stopped depends_on: db: condition: service_healthy db: image: postgres:16 environment: { POSTGRES_PASSWORD: example } healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 3s retries: 5start it again if it exits, unless you stopped itwritten as depends_on: [db], this waits only for db to startwait until the health check below passesa command run inside the db container: exit code 0 is healthyrun it every 5 secondsunhealthy after 5 failures in a rowdepends_on orders the starts. Only a health check makes one service wait until another is ready.A database counts as started seconds before it accepts connections, so a web container that connects at once fails.restart takes no (the default), on-failure, always or unless-stopped. Kubernetes gives these two jobs to probes and controllers.

healthcheck on db, and condition: service_healthy on web.

Lesson complete

You finished “Running containers”

Nicely done.

Open in a new tab