Skip to content

Docker

Basic commands

To check status of all containers:

docker ps

Add the -a flag to include stopped containers.

Stop a container:

docker stop container_name

Remove a container:

docker rm container_name

or to stop and remove in a single step:

docker rm -f container_name

To remove all stopped Docker containers:

docker container prune

To start a container:

docker start container_name

To restart a container:

docker restart container_name

Types of Docker storage

Volumes: Managed by Docker, stored in /var/lib/docker/volumes/ (on Linux), best for most use cases.

Bind mounts: Maps a host directory into the container. Useful for development.

Tmpfs: Temporary storage in memory. Disappears after container stops.

Volumes

Here is an example of a docker-compose.yaml volumes section with a mix of short syntax and long syntax for defining bind mounts:

volumes:
  - /path/to/config:/config  # bind mount that maps path on your host machine (left of :) with path inside the container (right of :)
  - /path/to/cache:/cache
  - type: bind  # these 3 lines map a path on your host machine (source) with path inside the container (target)
    source: /path/to/media
    target: /media

Both syntax are equivalent.

Set up Docker and Docker Compose

See Set up Docker and Docker Compose.

Start containers automatically

Using restart policies

Docker provides restart policies to control whether your containers start automatically when they exit, or when Docker restarts.

The following command starts container named containername and configures it to always restart, unless the container is explicitly stopped, or the daemon restarts.

docker run -d --restart unless-stopped containername

The following command changes the restart policy for an already running container:

docker update --restart unless-stopped containername

Using a process manager

You can also use a process manager like systemd. Create the systemd file:

nano /etc/systemd/system/docker-myproject.service
[Unit]
Description=Docker project
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStart=/usr/bin/docker start -a myproject
ExecStop=/usr/bin/docker stop -t 2 myproject

[Install]
WantedBy=default.target

Then, enable the service at startup:

sudo systemctl enable docker-myproject.service

!!! warning

Don't combine Docker restart policies with process managers, as this creates conflicts.