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.
-druns it in the background, and--name webgives it a name you can use later.docker logsshows its output.docker execruns 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 webPublish a port to reach a container from outside
-p 8080:80sends 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:80keeps it to your own machine.
Containers find each other by name on a shared network
- Create a network with
docker network create my-netand 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
readonlywhen the container should only read.
| Volume | Bind mount | |
|---|---|---|
| Lives in | A folder Docker manages | A host folder you choose |
| Best for | Databases and uploaded files | Source 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 stopsends 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.5caps it at 512 MB of memory and one and a half CPUs.- By default a container that exits stays down.
--restart unless-stoppedbrings it back after a crash or a Docker restart.