Setting Up a Private Docker Registry for Self-Hosted Containers
Introduction
A private Docker registry allows you to store and distribute your own container images securely without relying on public registries like Docker Hub. This is particularly useful for self-hosted projects, CI/CD pipelines, and internal development environments. In this guide, you’ll learn how to set up a private Docker registry on your server.
Step 1: Install Docker and Docker Compose
-
Update your system and install Docker:
sudo apt update && sudo apt install -y docker.io
-
Enable and start the Docker service:
sudo systemctl enable --now docker
-
Install Docker Compose:
sudo apt install -y docker-compose
Step 2: Deploy the Docker Registry Container
-
Create a directory for the registry:
mkdir -p ~/docker-registry && cd ~/docker-registry
-
Create a
docker-compose.yml
file:sudo nano docker-compose.yml
-
Add the following content:
version: '3'
services:
registry:
image: registry:2
restart: always
ports:
- 5000:5000
volumes:
- ./data:/var/lib/registry
-
Save the file and start the registry:
docker-compose up -d
Step 3: Configuring Nginx as a Reverse Proxy (Optional)
-
Install Nginx:
sudo apt install -y nginx
-
Create an Nginx configuration file:
sudo nano /etc/nginx/sites-available/docker-registry
-
Add the following configuration:
server {
listen 80;
server_name registry.yourdomain.com;
location / {
proxy_pass http://localhost:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
-
Enable the configuration and restart Nginx:
sudo ln -s /etc/nginx/sites-available/docker-registry /etc/nginx/sites-enabled/
sudo systemctl restart nginx
Step 4: Secure the Registry with Authentication
-
Install Apache utilities for password protection:
sudo apt install -y apache2-utils
-
Create a credentials file:
sudo htpasswd -Bc /etc/docker-registry/htpasswd myuser
-
Update your
docker-compose.yml
file to include authentication:
services:
registry:
image: registry:2
restart: always
ports:
- 5000:5000
environment:
REGISTRY_AUTH: htpasswd
REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
volumes:
- ./data:/var/lib/registry
- /etc/docker-registry:/auth
-
Restart the registry:
docker-compose down && docker-compose up -d
Step 5: Pushing and Pulling Images from Your Private Registry
-
Tag an image for your private registry:
docker tag myimage registry.yourdomain.com/myimage:latest
-
Authenticate with the registry:
docker login registry.yourdomain.com
-
Push the image:
docker push registry.yourdomain.com/myimage:latest
-
Pull the image on another machine:
docker pull registry.yourdomain.com/myimage:latest
Conclusion
You now have a private Docker registry running on your server, secured with authentication and accessible via a custom domain. This setup allows you to manage container images efficiently while keeping them private and under your control. Consider adding SSL with Let’s Encrypt for enhanced security.