BASH

Gracefully Restart a Web Service

Implement a Bash script to gracefully restart a web service (e.g., Nginx, Apache, or a Node.js process) using systemd, ensuring minimal downtime and proper resource management during deployments.

#!/bin/bash

SERVICE_NAME="$1" # e.g., nginx, apache2, your_node_app.service

if [ -z "$SERVICE_NAME" ]; then
    echo "Usage: $0 <service_name>"
    echo "Example: $0 nginx"
    exit 1
fi

echo "Attempting to gracefully restart service: ${SERVICE_NAME}..."

# Check if the service exists
if ! systemctl list-units --type=service --all | grep -q "${SERVICE_NAME}"; then
    echo "Error: Service '${SERVICE_NAME}' not found. Please ensure it is a valid systemd service."
    exit 1
fi

# Attempt to restart the service
if systemctl restart "${SERVICE_NAME}"; then
    echo "Service '${SERVICE_NAME}' restarted successfully."
    # Optional: Check service status
    systemctl status "${SERVICE_NAME}" --no-pager
else
    echo "Error: Failed to restart service '${SERVICE_NAME}'. Check logs for details."
    exit 1
fi
How it works: This script provides a clean way to restart systemd services, commonly used for web servers like Nginx or application processes like Node.js apps. It takes the service name as an argument, validates its existence, and then uses `systemctl restart` to gracefully stop and start the service. This ensures that the service is brought down and up in a controlled manner, preventing abrupt interruptions and making it ideal for deployment pipelines.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs