In this post, I’ll explain a very simple yet useful concept. I’m using Docker to manage a couple of containers in a few servers without using any management software since the environment isn’t big and complicated. Creating the containers for once is easy, it requires only a single line command. Yet, I’ve to save that command for later use; because it also contains my configurations.
In this example, we use the port, name, volume, and path parameters. This command will be needed in the future when we need to regenerate (eg. update) the container.
docker run -d -p 3000:3000 --restart=unless-stopped -v grafana:/var/lib/grafana -v /monitoring/grafana/grafana.ini:/etc/grafana/grafana.ini:ro -v /monitoring/grafana/ldap.toml:/etc/grafana/ldap.toml:ro --name grafana grafana/grafana:latest
Saving these commands in your notepad is a bad way to handle this process. Like every normal person, we want to keep these configurations in a well-structured file. We can utilize Systemd Unit Files to solve this problem. I’ll continue with the Grafana example.
- Create a systemd file
vim /etc/systemd/system/grafana.service
- Add the required content
[Unit]
Description=Grafana
Requires=docker.service
After=docker.service
[Service]
ExecStart=/usr/bin/docker run --rm --name=%n -p 3000:3000 --network=grafana -v grafana:/var/lib/grafana -v /monitoring/grafana/grafana.ini:/etc/grafana/grafana.ini:ro -v /monitoring/grafana/ldap.toml:/etc/grafana/ldap.toml:ro grafana/grafana:latestExecStop=/usr/bin/docker rm -f %n
Restart=always
[Install]
WantedBy=multi-user.target
- Daemon-Reload
Whenever we change unit files, we need to run daemon-reload so that systemd reloads the new configurations.
systemctl daemon-reload
- Start the service
It’s done. Now we can use systemctl commands to manage the service. Start the container (service).
systemctl start grafana.service
Make it start automatically on boot. systemctl enable grafana.service
We don’t need to remove the container and create a new one with a long command. We can simply use systemctl restart grafana.service
.