Automatically Restart Docker Containers using systemd

Umar khan - Sep 21 - - Dev Community

Managing Docker containers with systemd ensures that your containers automatically start on boot,
restart on failure, and stop gracefully. This guide will cover the setup for Nginx.

## Step-by-Step Guide
**
### 1. Running Your Docker Containers**
First, start your Docker containers using the following commands:

NGIN Container

‘’’ bash
docker run -d --name=some-nginx nginx:latest-
‘’’
-d: Run container in detached mode.

  • --name=some-nginx: Name the container some-nginx.. . **### 2. Creating systemd Service Unit Files **Create systemd service unit files for each container. This example will guide you through creating a service file for the NGINX container. #### Nginx Service Unit File Create the service file:
sudo nano /etc/systemd/system/nginx_container.service
Enter fullscreen mode Exit fullscreen mode

Paste the following content:

[Unit]
Description=Nginx Docker Container
Requires=docker.service
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker start -a some-nginx
ExecStop=/usr/bin/docker stop -t 2 some-nginx
[Install]
WantedBy=default.target
Enter fullscreen mode Exit fullscreen mode

### 3. Enabling and Starting the Services
**
Enable and start the services using the following commands :
**#### Nginx Service

sudo systemctl enable nginx_container.service
sudo systemctl start nginx_container.service
Enter fullscreen mode Exit fullscreen mode

**### 4. Checking Status and Logs
**Check the status and logs of each service to ensure they are running correctly:

Nginx Service Status and Logs

sudo systemctl status nginx_container.service
sudo journalctl -u nginx_container.service
Enter fullscreen mode Exit fullscreen mode

After reboot or crash of server the container automatically restar

.
Terabox Video Player