Back to articles
DevOps & Systems

Green DevOps: Optimizing Costs and Energy with Script-Driven Container Migration During Low-Traffic Hours

Green DevOps is a sustainable software development methodology focused on reducing operational costs and energy consumption in cloud environments. An effective technique involves...

DPTCloud Engineering4 min read
Green DevOps: Optimizing Costs and Energy with Script-Driven Container Migration During Low-Traffic Hours

Image credit: EdWhiteImages · Pixabay Content License

Green DevOps is a sustainable software development methodology focused on reducing operational costs and energy consumption in cloud environments. An effective technique involves automatically migrating Docker containers from VPS hosts during low-traffic periods—typically overnight or weekends—using scripts. This approach conserves electricity and lowers hosting expenses, especially when using high-performance solutions like NVMe Cloud VPS for Docker, Nginx & Databases or High-Performance Dedicated Servers for Production Clusters. This guide demonstrates how to build a Python script to monitor system load, identify low-traffic windows, and migrate containers to lower-cost VPS instances or power down unused servers.

Introduction to Green DevOps and Its Benefits

Green DevOps integrates software development practices with environmentally conscious operations. As cloud costs rise, optimizing resource usage becomes essential. Migrating containers during low-traffic hours not only reduces energy use but also cuts hosting costs, particularly when running testing or development applications with minimal load at night. A common scenario involves moving non-critical containers from production-grade infrastructure to cost-effective NVMe Cloud VPS or temporarily shutting down underutilized VPS instances. This strategy aligns with broader Green DevOps goals, such as those described in the article Automating VPS Snapshot Backup and Shutdown for Green DevOps.

Prerequisites and Environment Setup

To implement this solution, you will need:

  • A VPS or dedicated server account (e.g., NVMe Cloud VPS for Docker, Nginx & Databases).
  • Docker installed on all servers.
  • Python 3.8 or higher with the docker and requests libraries.
  • SSH or API access to control the servers.
  • A scheduled job (cron) or orchestration tool like Kubernetes to run the script.

For additional context on automation, see Automating VPS Snapshot Backup and Shutdown for Green DevOps.

Writing the Automated Container Migration Script

The Python script below checks CPU and RAM usage, determines if the current time falls within a low-traffic window (e.g., 11 PM to 6 AM), and migrates containers tagged as "testing" or "development" to a target VPS or stops them.

#!/usr/bin/env python3
import docker
import psutil
import time
import requests
import os

# Configuration
TARGET_VPS_IP = "192.168.1.100"  # IP of target VPS
TARGET_VPS_API = f"http://{TARGET_VPS_IP}:2375"  # Docker API of target VPS
SOURCE_CLIENT = docker.APIClient(base_url='unix://var/run/docker.sock')
TARGET_CLIENT = docker.APIClient(base_url=TARGET_VPS_API)

# List of container tags to migrate
CONTAINER_TAGS = ["testing", "development"]

def is_low_traffic():
    "Check if current time is during low-traffic hours"
    current_hour = time.localtime().tm_hour
    return 23 <= current_hour or current_hour < 6  # 11 PM to 6 AM

def get_container_list():
    "Get list of running containers"
    containers = SOURCE_CLIENT.containers()
    return [c for c in containers if any(tag in c['Names'][0] for tag in CONTAINER_TAGS)]

def stop_and_move_container(container_id, container_name):
    "Stop and move container to target VPS"
    try:
        print(f"Moving container {container_name} (ID: {container_id})...")
        # Stop container on source
        SOURCE_CLIENT.stop(container_id)
        # Wait for container to stop
        SOURCE_CLIENT.wait(container_id)
        # Export container
        container_data = SOURCE_CLIENT.export(container_id)
        # Upload container to target VPS
        response = requests.post(f"{TARGET_VPS_API}/containers/create", data=container_data, headers={'Content-Type': 'application/octet-stream'})
        if response.status_code == 201:
            container_id_target = response.json()['Id']
            TARGET_CLIENT.start(container_id_target)
            print(f"Success: Container {container_name} moved and started on target VPS.")
        else:
            print(f"Error: Failed to upload container. Status code: {response.status_code}")
    except Exception as e:
        print(f"Error moving container: {e}")

def main():
    if not is_low_traffic():
        print("Not low-traffic hours. Skipping.")
        return

    containers = get_container_list()
    if not containers:
        print("No containers to move.")
        return

    for container in containers:
        container_id = container['Id']
        container_name = container['Names'][0]
        stop_and_move_container(container_id, container_name)

if __name__ == "__main__":
    main()

Run this script periodically (e.g., every hour) using cron. Configure cron with: crontab -e and add: 0 * * * * /path/to/your/script.py.

Testing and Troubleshooting

To ensure the script functions correctly, perform these checks:

  • Run the script manually to verify output.
  • Ensure the target VPS Docker API is enabled and accessible.
  • Use docker ps on both servers to confirm container migration.
  • Monitor script logs for errors.

If containers fail to migrate, verify permissions and network connectivity. Alternatively, pause containers instead of moving them and restart during peak hours.

Conclusion

Automated container migration during low-traffic hours is a key Green DevOps practice that reduces costs and energy use. With a simple Python script and automation tools, you can efficiently optimize cloud resources. Explore additional strategies like multi-cloud deployment in Multi-Cloud VPS Strategy: Leveraging AWS, DigitalOcean, and Linode with Kubernetes for High Availability.

DPTCloud Tier III Infrastructure

Recommended NVMe Cloud VPS Plans to Deploy This Setup

Enterprise RAID 10 NVMe SSDs, CMC & FPT District 9 uplinks with Anycast Anti-DDoS and 99.99% SLA.

View 22 VPS Plans
ECO · vn-02

VPS-2E

94.600 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 2 GB
  • SSD: 30 GB NVMe
ECO · vn-02Recommended

VPS-3E

170.500 ₫ / mo

10% VAT included

  • CPU: 2 vCPU
  • RAM: 4 GB
  • SSD: 50 GB NVMe
BASIC · vn-01Recommended

VPS-05

457.600 ₫ / mo

10% VAT included

  • CPU: 4 vCPU
  • RAM: 8 GB
  • SSD: 50 GB NVMe

Related Articles

View all
ZaloZalo SupportDiscord0384 753 478