Systemd Service for docker-compose

Docker-compose can be used to deploy simple applications, it gives ability to start set of dependent containers or services as a whole application. It is simple to use and configure.

There are alternatives like docker swarm or Kubernetes which are suitable for complex and enterprise applications.


Docker compose provides simplicity for deploying simple applications. When server is restarted docker containers will not start at automatically. This can be solved by creating custom systemd service.

  • Write docker-compose.yml file with all services/components, below is the django app example taken from docker documentation.
version: "3.9"
   
services:
  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
Example from docs.docker.com
  • You can start web and db application using docker-compose up
# will bring up all services in docker-compose.yml
docker-compose up -d

# pass yml file with -f flag
docker-compose up -f application.yml
  • -d flag will start docker services in daemon/background mode
  • Write systemd service in /etc/systemd/system/myapp.service
[Unit]
Description=Service for myapp
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
WorkingDirectory=/root/bootvar
Environment=COMPOSE_HTTP_TIMEOUT=600
ExecStart=/usr/bin/env /usr/bin/docker-compose -f /root/bootvar/docker-compose.yml up -d
ExecStop=/usr/bin/env /usr/bin/docker-compose -f /root/bootvar/docker-compose.yml stop
StandardOutput=syslog
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
/etc/systemd/system/myapp.service
  • Now you have created myapp service, enable it and start the service. Enabling service will make sure to start this service at server startup.
# will enable service to start at server bootup
systemctl enable myapp

# start service ( Executes ExecStart command )
systemctl start myapp

This way you can make sure your docker-compose service stays up and running after server restart.

Suhas Adhav
In love with web3, DApps and Blockchain Technology | DevOps Expert | Kubernetes | Docker | Jenkins | Cloud | Hadoop
The Internet