Purpose of this article to demonstrate how to use systemd for Docker Compose.
What is systemd
?
Systemd is a system and service manager for Linux operating systems. It is designed to replace the traditional init system and provides a unified interface for managing system services and processes. Systemd is responsible for starting and stopping services, managing dependencies between services, and handling system shutdown and reboot.
What is docker-compose
?
Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to define your application’s services in a YAML file, and then use a single command to create and start all the services from your configuration.
Let’s Begin
1. Create a project directory:
1
2
| mkdir -p /srv/myapp
cd /srv/myapp
|
2. Create a docker-compose.yml
file with the following content:
1
2
3
4
5
6
| version: '3'
services:
web:
image: nginx:latest
ports:
- "3000:80"
|
3. Create a file /etc/systemd/system/myapp.service
with the following content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| [Unit]
Description=MyApp
After=docker.service
Requires=docker.service
[Service]
Type=simple
WorkingDirectory=/srv/myapp
ExecStart=/usr/bin/docker-compose up
ExecStop=/usr/bin/docker-compose down
Restart=always
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
|
After
in Unit
section is used to specify the dependencies between services. In this case, we want to ensure that the docker.service
is started before our myapp.service
.
Requires
in Unit
section is used to specify the dependencies between services. In this case, we want to ensure that the docker.service
is started before our myapp.service
.
4. Reload systemd:
1
| sudo systemctl daemon-reload
|
5. Start the service:
1
| sudo systemctl start myapp.service
|
6. Enable the service:
1
| sudo systemctl enable myapp.service
|
5. Verify the service status:
1
| sudo systemctl status myapp.service
|