Skip to content
Engineering Bible
Docker

Docker on running, networking and storage

docker run starts a container from an image

  • It pulls the image first if your machine doesn't have it yet.
  • -d runs it in the background, and --name web gives it a name you can use later.
  • docker logs shows its output. docker exec runs a command, like a shell, inside it.
docker run -d --name web -p 127.0.0.1:8080:80 nginx
docker logs web
docker exec -it web sh
docker stop web
docker rm web
Start a web server, read its output, open a shell inside it, then stop and remove it.

Publish a port to reach a container from outside

  • -p 8080:80 sends port 8080 on the host to port 80 in the container. Host comes first.
  • A port you don't publish can't be reached from outside the host.
  • A published port listens on every address by default, so other machines can reach it.
  • -p 127.0.0.1:8080:80 keeps it to your own machine.

Containers find each other by name on a shared network

  • Create a network with docker network create my-net and start containers with it.
  • Docker's built-in DNS then turns a container's name into its address: http://api:3000.
  • On the default network, containers can't look each other up by name.
  • Only containers on the same network can talk, so a network is also a wall.

Data in a container dies with it, so use a volume

  • Files a container writes go to its writable layer, which is removed with the container.
  • A volume is storage that Docker manages outside the container. It outlives the container.
  • A bind mount shows a folder from the host inside the container: handy for source code.
  • A bind mount can change host files. Add readonly when the container should only read.
VolumeBind mount
Lives inA folder Docker managesA host folder you choose
Best forDatabases and uploaded filesSource code while developing
Flag--mount type=volume,src=data,dst=/data--mount type=bind,src=/code,dst=/app

Containers are asked to stop, then forced

  • docker stop sends SIGTERM, a polite stop signal, to the container's main process.
  • If the process is still running after 10 seconds, Docker kills it with SIGKILL.
  • Write CMD ["node", "server.js"] with brackets, so your app is that main process.
  • Without brackets a shell runs your app and doesn't pass the signal on.

Set limits and a restart policy

  • By default a container has no limits and can use all the memory and CPU the host has.
  • --memory=512m --cpus=1.5 caps it at 512 MB of memory and one and a half CPUs.
  • By default a container that exits stays down.
  • --restart unless-stopped brings it back after a crash or a Docker restart.
Docker in four pages3 / 4