Table of Contents
Deploying Docker containers on CentOS and RHEL systems can be streamlined using systemd, the system and service manager. This approach allows you to manage containers as system services, ensuring they start automatically on boot and can be easily monitored or restarted.
Prerequisites
- CentOS or RHEL installed with root or sudo privileges
- Docker installed and running
- Basic knowledge of systemd and Docker commands
Installing Docker
If Docker is not already installed, you can install it using the following commands:
For CentOS 7/8 and RHEL 7/8:
“`bash sudo yum install -y yum-utils sudo yum-config-manager –add-repo https://download.docker.com/linux/centos/docker-ce.repo sudo yum install -y docker-ce docker-ce-cli containerd.io sudo systemctl start docker sudo systemctl enable docker “`
Creating a Systemd Service for Docker Container
To run a Docker container as a systemd service, create a service unit file. For example, to run an Nginx container:
1. Create a new service file:
sudo nano /etc/systemd/system/nginx-docker.service
2. Add the following content:
[Unit]
Description=Nginx Docker Container
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker run –rm –name nginx-container -p 80:80 nginx
ExecStop=/usr/bin/docker stop nginx-container
[Install]
WantedBy=multi-user.target
Managing the Service
Once the service file is created, reload systemd to recognize the new service:
sudo systemctl daemon-reload
Enable the service to start on boot:
sudo systemctl enable nginx-docker
Start the container:
sudo systemctl start nginx-docker
Monitoring and Troubleshooting
You can check the status of your container service with:
sudo systemctl status nginx-docker
If needed, view Docker logs directly:
sudo journalctl -u nginx-docker
Conclusion
Using systemd to manage Docker containers on CentOS and RHEL provides a reliable way to ensure your containers run consistently and are easy to control. This method integrates container management into the system’s native service management framework, simplifying deployment and maintenance tasks.