BLOG POSTS
How to Install and Use Docker on latest CentOS

How to Install and Use Docker on latest CentOS

Docker has revolutionized the way we deploy and manage applications by providing lightweight, portable containers that eliminate the “it works on my machine” problem. For CentOS users, getting Docker up and running opens up a world of streamlined development workflows, consistent production deployments, and simplified server management. This guide walks you through installing Docker on the latest CentOS, configuring it properly, and demonstrates practical usage scenarios that’ll get you containerizing applications like a pro.

Understanding Docker on CentOS

Docker operates as a containerization platform that packages applications and their dependencies into lightweight, portable containers. Unlike traditional virtual machines that virtualize entire operating systems, Docker containers share the host OS kernel while maintaining isolated user spaces. This approach dramatically reduces resource overhead while maintaining security boundaries.

On CentOS, Docker runs as a system service (daemon) that manages container lifecycle, image storage, and network configuration. The Docker engine consists of three main components: the Docker daemon (dockerd), the Docker CLI client, and containerd for container runtime management.

Installation Methods Comparison

Installation Method Pros Cons Best For
Official Repository Latest stable version, automatic updates, official support Requires repository setup Production environments
RPM Package Offline installation, version control Manual updates, dependency management Air-gapped systems
CentOS Repository Simple installation Older versions, limited features Quick testing only

Step-by-Step Installation Guide

Before installing Docker, ensure your CentOS system meets the requirements. Docker requires CentOS 7 or later with a 64-bit architecture and kernel version 3.10 or higher.

First, update your system and remove any existing Docker installations:

sudo dnf update -y
sudo dnf remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine

Install required packages for repository management:

sudo dnf install -y dnf-utils device-mapper-persistent-data lvm2

Add the official Docker repository:

sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

Install Docker CE (Community Edition):

sudo dnf install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Start and enable the Docker service:

sudo systemctl start docker
sudo systemctl enable docker

Verify the installation by running the hello-world container:

sudo docker run hello-world

Post-Installation Configuration

To avoid using sudo with every Docker command, add your user to the docker group:

sudo usermod -aG docker $USER
newgrp docker

Configure Docker daemon settings by creating or editing the daemon configuration file:

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<EOF
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ]
}
EOF

Restart Docker to apply configuration changes:

sudo systemctl restart docker

Essential Docker Commands and Usage

Here are the fundamental Docker commands every user should master:

# Image management
docker images                    # List local images
docker pull nginx:latest        # Pull image from registry
docker rmi image_name           # Remove image
docker build -t myapp:v1 .     # Build image from Dockerfile

# Container operations
docker ps                       # List running containers
docker ps -a                   # List all containers
docker run -d --name web nginx # Run container in background
docker stop container_name     # Stop container
docker rm container_name       # Remove container
docker exec -it web bash      # Execute command in running container

# System management
docker system df              # Show disk usage
docker system prune          # Clean up unused resources
docker logs container_name   # View container logs

Real-World Use Cases and Examples

Let’s explore practical scenarios where Docker shines on CentOS systems.

Web Application Deployment:

Create a simple web server setup using Docker Compose. First, create a project directory and docker-compose.yml:

mkdir webapp && cd webapp
cat > docker-compose.yml <<EOF
version: '3.8'
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./html:/usr/share/nginx/html
  database:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: secretpassword
      MYSQL_DATABASE: webapp
    volumes:
      - db_data:/var/lib/mysql
volumes:
  db_data:
EOF

Create content and launch the application:

mkdir html
echo "<h1>Hello from Docker!</h1>" > html/index.html
docker compose up -d

Development Environment Setup:

For developers working on multiple projects, Docker provides isolated environments. Here’s a Python development container example:

cat > Dockerfile <<EOF
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 5000
CMD ["python", "app.py"]
EOF

Performance Considerations and Optimization

Docker performance on CentOS can be optimized through several approaches:

  • Storage Driver Selection: Use overlay2 for better performance compared to devicemapper
  • Resource Limits: Set memory and CPU constraints to prevent resource exhaustion
  • Multi-stage Builds: Reduce image sizes by using multi-stage Dockerfiles
  • Image Layering: Optimize Dockerfile instruction order to leverage layer caching

Example resource-limited container:

docker run -d --name limited-app --memory="512m" --cpus="1.0" nginx:alpine

Common Issues and Troubleshooting

SELinux Compatibility:

CentOS runs with SELinux enabled by default, which can cause permission issues with Docker volumes. Use the :z or :Z flags for volume mounts:

docker run -v /host/path:/container/path:z image_name

Firewall Configuration:

Docker manipulates iptables rules, which may conflict with firewalld. Configure firewalld to work with Docker:

sudo firewall-cmd --zone=docker --add-interface=docker0 --permanent
sudo firewall-cmd --reload

Storage Space Issues:

Monitor Docker disk usage and clean up regularly:

docker system df
docker system prune -a --volumes

Container Networking Problems:

Check Docker’s default bridge network configuration:

docker network ls
docker network inspect bridge

Security Best Practices

Implementing proper security measures is crucial for production Docker deployments:

  • Run containers as non-root users when possible
  • Use official base images and keep them updated
  • Scan images for vulnerabilities using tools like Trivy or Clair
  • Implement resource limits to prevent DoS attacks
  • Use secrets management instead of environment variables for sensitive data

Example of running a container with limited privileges:

docker run --user 1000:1000 --read-only --tmpfs /tmp nginx:alpine

Integration with CentOS Services

Docker integrates well with existing CentOS infrastructure. For production deployments, consider using systemd service files for container management:

sudo tee /etc/systemd/system/webapp.service <<EOF
[Unit]
Description=Web Application Container
After=docker.service
Requires=docker.service

[Service]
ExecStart=/usr/bin/docker run --rm --name webapp -p 8080:80 nginx:alpine
ExecStop=/usr/bin/docker stop webapp
Restart=always

[Install]
WantedBy=multi-user.target
EOF

Enable and start the service:

sudo systemctl enable webapp.service
sudo systemctl start webapp.service

Monitoring and Logging

Effective monitoring helps maintain healthy Docker deployments. Configure log rotation and monitoring:

# View container resource usage
docker stats

# Monitor system events
docker events

# Configure log rotation in daemon.json
{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "5"
  }
}

For comprehensive server management and hosting solutions that complement your Docker deployments, consider managed VPS services or dedicated servers that provide the robust infrastructure needed for production containerized applications.

Docker on CentOS provides a powerful foundation for modern application deployment and development workflows. With proper installation, configuration, and security practices, you’ll have a reliable containerization platform that scales with your needs. The combination of CentOS’s stability and Docker’s flexibility creates an ideal environment for both development and production workloads.

For additional resources and detailed documentation, visit the official Docker installation guide for CentOS and the Docker command reference documentation.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked