Installing Docker and Docker Compose: watch out for ports that bypass your firewall
In this guide you install Docker Engine and the Compose plugin from Docker's official repository on Ubuntu, Debian and AlmaLinux, run your first Compose project, and close a gap that many people notice too late: published container ports are exposed to the internet without ever passing through your UFW or firewalld rules.
Before you install: why the official repository?
The docker.io package in the Ubuntu and Debian repositories often lags behind Docker's current release, and the Compose v2 plugin is packaged differently. The method Docker documents is to add the download.docker.com repository with its signing key and install the docker-ce packages from there. Security fixes then arrive without waiting for the distribution's schedule.
- Version: Check which distribution releases Docker supports in the official installation docs. For a new installation, choose Ubuntu 24.04 or 26.04 LTS, Debian 12 or 13, or AlmaLinux 9; interim releases such as Ubuntu 24.10 and 25.04 are supported only for a short time.
- Restore point: If you are installing on a server that already holds data, first take a snapshot with the Snapshots tool in the client area. You can keep at most 2 snapshots at a time, and a snapshot is not a substitute for a backup (see the snapshot guide).
- Privileges: The commands assume you are running them as root. If you work as a user with sudo rights, prefix the commands with
sudo, and write the| teepart of the repository line as| sudo tee.
If you previously installed Docker from distribution packages, remove them first to avoid conflicts. This does not delete the images, containers or volumes under /var/lib/docker:
for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do apt-get remove $pkg; doneInstallation: Ubuntu, Debian and AlmaLinux
On Ubuntu and Debian the repository signing key is downloaded to /etc/apt/keyrings, the repository line is written with the server's architecture and release codename, and then the Engine (docker-ce), the client, containerd, Buildx and the Compose plugin are installed.
Ubuntu
apt-get update
apt-get install -y ca-certificates curl
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
$(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | \
tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-pluginDebian
On Debian only the repository URL changes, and the release codename is read directly from the VERSION_CODENAME variable:
apt-get update
apt-get install -y ca-certificates curl
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian \
$(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-pluginOn these two distributions the Docker service starts by itself after installation and is enabled at boot.
AlmaLinux 9
On the RHEL family you use Docker's rhel repository. If Podman or runc is installed, it is removed first because it conflicts with the Docker packages; the "No match for argument" message for packages that are not installed is normal.
dnf remove docker docker-client docker-client-latest docker-common docker-latest \
docker-latest-logrotate docker-logrotate docker-engine podman runc
dnf -y install dnf-plugins-core
dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo
dnf install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now dockerDuring installation dnf asks you to accept Docker's GPG key; compare the fingerprint on screen with the one in the official docs, and stop if they do not match. On the RHEL family the service does not start by itself; the last line both starts it and enables it at boot.
Verification and the docker group
systemctl status docker --no-pager
docker run --rm hello-world
docker compose version
docker info --format '{{.ServerVersion}} {{.LoggingDriver}} {{.CgroupDriver}}'If the hello-world container prints "Hello from Docker!" and exits, the Engine, image pulls and container networking are all working.
Adding a user to the docker group is equivalent to giving that user root access without a password: they can mount the server's root directory into a container and change any file. Grant the group only to accounts you would trust with root; on servers used by several people, consider the rootless mode described in Docker's security docs.
usermod -aG docker deploy
# After the deploy user logs out and back in:
id deploy
docker run --rm hello-worldYour first Compose project: WordPress and MariaDB
Three decisions in the example below are deliberate. The web container is published only on 127.0.0.1 and exposed to the outside through Nginx running on the server. The database has no ports entry at all. Data lives in named volumes, which survive even if the containers are deleted. The restart: unless-stopped policy brings containers back after the server restarts but leaves the ones you stopped manually stopped.
First create the project directory and the .env file that holds the passwords. Using hexadecimal passwords avoids problems such as Compose treating a $ character in a password as a variable:
mkdir -p /opt/wordpress && cd /opt/wordpress
printf 'DB_PASSWORD=%s\nDB_ROOT_PASSWORD=%s\n' "$(openssl rand -hex 24)" "$(openssl rand -hex 24)" > .env
chmod 600 .envThen create /opt/wordpress/compose.yaml. Compose v2 does not need a version: line at the top of the file; if you add one, you get an "obsolete" warning.
services:
db:
image: mariadb:11.4
restart: unless-stopped
environment:
MARIADB_DATABASE: wordpress
MARIADB_USER: wordpress
MARIADB_PASSWORD: ${DB_PASSWORD}
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
volumes:
- db_data:/var/lib/mysql
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
# No ports entry: only containers in this project can reach the database
wordpress:
image: wordpress:latest
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_NAME: wordpress
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: ${DB_PASSWORD}
ports:
- "127.0.0.1:8080:80" # reachable only from the server itself
volumes:
- wp_data:/var/www/html
volumes:
db_data:
wp_data:cd /opt/wordpress
docker compose config --quiet && docker compose up -d
docker compose ps
docker compose logs --tail=50 wordpress
curl -I http://127.0.0.1:8080Pin the major version of the database image (11.4 in the example): jumping a major version may require upgrading the data directory, and you do not want that to happen silently during a routine pull. In production, prefer a specific version tag over latest for the application image as well.
The port trap: why published ports bypass your firewall
When you write "8080:80" in a Compose file, Docker adds a destination NAT (DNAT) rule to the iptables nat table. A packet arriving at the server on port 8080 is rewritten to the container's internal address before the routing decision is made; it no longer counts as traffic for the server itself but as traffic forwarded to a container, so it passes through the FORWARD chain instead of INPUT. Your UFW rules live in the INPUT chain and never come into play, and the zone rules you define in firewalld for services on the server do not stop this traffic either. As a result, ufw status shows 8080 as closed while the port is reachable from the internet. This is especially dangerous for databases (3306, 5432), Redis (6379) and admin interfaces.
| Compose notation | Who can connect? | Firewall effect |
|---|---|---|
"8080:80" | Anyone, on every address of the server | UFW and firewalld rules do not apply |
"127.0.0.1:8080:80" | Only the server itself (Nginx, an SSH tunnel) | No access from outside |
"203.0.113.20:8080:80" | Anyone, but only on that address (e.g. an additional IP) | Still bypasses UFW and firewalld rules |
No ports entry | Only containers on the same Docker network | Not exposed outside the server |
Fix 1: Publish on the local address only and expose it through Nginx
The 127.0.0.1:8080:80 notation in the example opens the port only on the server's loopback address. Nginx running on the server publishes the site to the outside world as a reverse proxy, so you deliberately open only ports 80 and 443 in the firewall and manage the TLS certificate in one place. To install Nginx, see the LEMP guide; for the certificate, see the Let's Encrypt guide. Save the configuration below as /etc/nginx/sites-available/wordpress on Ubuntu and Debian, or as /etc/nginx/conf.d/wordpress.conf on AlmaLinux:
server {
listen 80;
server_name example.com www.example.com;
client_max_body_size 64m;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}# Ubuntu/Debian: enable /etc/nginx/sites-available/wordpress
ln -s /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/wordpress
nginx -t && systemctl reload nginx
curl -I -H 'Host: example.com' http://127.0.0.1Fix 2: Never publish database ports
Containers in the same Compose project reach each other by service name on a shared internal network; WordPress connects to the database at db:3306, and no port has to be published for that. For maintenance, use docker compose exec db mariadb -u root -p. If you need to connect with a database client on your own computer, publish the port only as 127.0.0.1:3306:3306 and open an SSH tunnel: ssh -L 3307:127.0.0.1:3306 root@SERVER_IP. Then point the client at 127.0.0.1:3307.
Fix 3: Filter a port that must stay public with the DOCKER-USER chain
If a port has to stay open to the outside but should be reachable only from certain addresses, add the rule to the DOCKER-USER chain, which is evaluated before Docker's own rules. --ctorigdstport matches the server port before address translation, and --ctdir ORIGINAL makes sure the return traffic of connections started by the containers themselves is not affected.
# Find the external interface used by the default route (e.g. ens160)
IFACE=$(ip route show default | awk '{print $5; exit}')
# Allow only 203.0.113.10 to reach port 8080
iptables -I DOCKER-USER -i "$IFACE" -p tcp -m conntrack --ctorigdstport 8080 --ctdir ORIGINAL ! -s 203.0.113.10 -j DROP
iptables -L DOCKER-USER -n -v --line-numbersThis rule is lost when the server reboots, and making it persistent takes extra configuration, so prefer Fix 1 first. Writing "iptables": false in /etc/docker/daemon.json may look like a fix, but it breaks container networking and port forwarding; we do not recommend it.
Verification: test from inside and outside
# On the server: which ports are listening on which addresses?
ss -tulpn | grep -E ':(80|443|8080|3306)\s'
docker compose ps
# From another Linux or macOS machine outside the server:
nc -vz -w 3 SERVER_IP 8080
nc -vz -w 3 SERVER_IP 3306
nc -vz -w 3 SERVER_IP 443In the ss output you should see 127.0.0.1:8080; if you see 0.0.0.0:8080, the port is open to everyone. From outside, expect a refused connection or a timeout for 8080 and 3306 and a successful connection for 443. From a Windows computer you can run the same test in PowerShell with Test-NetConnection SERVER_IP -Port 8080. For firewall rules on the server, see the UFW and firewalld guide.
Maintenance: log limits, updates and backups
Keep log files from filling the disk
By default Docker uses the json-file logging driver with no size limit, so the log of a chatty container can grow to gigabytes under /var/lib/docker/containers/. Set a limit in /etc/docker/daemon.json, the global configuration file of the Docker service. If the file already exists, add the keys while keeping the existing ones:
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}dockerd --validate --config-file=/etc/docker/daemon.json
systemctl restart docker
cd /opt/wordpress && docker compose up -d --force-recreate
docker inspect --format '{{.HostConfig.LogConfig}}' wordpress-wordpress-1This setting applies only to newly created containers; existing containers need --force-recreate. Restarting the Docker service briefly stops running containers, so do it at a quiet time. A single syntax error in the file keeps Docker from starting at all; check it with dockerd --validate before you restart.
If the disk is already full, start with the steps in the disk full guide.
Updates and cleanup
Update your images regularly. pull downloads new images, and up -d recreates only the containers whose image changed; the data in volumes is preserved:
cd /opt/wordpress
docker compose pull
docker compose up -d
docker image prune -f
docker system dfdocker image prune removes only untagged (dangling) images; the -a flag removes every image not used by a container. docker system df shows how much space images, containers and volumes take up. Do not run docker volume prune or docker system prune --volumes before you have checked which volumes would be deleted with docker volume ls.
Docker Engine is updated with the operating system packages (apt-get upgrade or dnf upgrade), and an update restarts your containers. On Ubuntu and Debian, unattended-upgrades in its default configuration watches only the distribution's own repositories, so you update the packages from the Docker repository yourself (see automatic security updates).
Back up your volumes
Volumes need a backup that is independent of snapshots and stored outside the server. Copying the data directory of a running database can produce an inconsistent backup; take a dump from the database instead, and archive file volumes by mounting them read-only:
cd /opt/wordpress
mkdir -p /root/backup
# Database dump: a consistent copy without locking InnoDB tables
docker compose exec -T db sh -c 'exec mariadb-dump -uroot -p"$MARIADB_ROOT_PASSWORD" --single-transaction --routines --triggers --all-databases' \
| gzip > /root/backup/wp-db-$(date +%F).sql.gz
# Mount the files volume read-only and archive it (check the name with docker volume ls)
docker run --rm -v wordpress_wp_data:/data:ro -v /root/backup:/backup alpine \
tar czf /backup/wp-files-$(date +%F).tar.gz -C /data .
ls -lh /root/backupTo move these archives to another server with restic, see the server backup strategy guide. Before a major image or Compose change, take a short-lived restore point with Snapshots and delete it once you have verified the change.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
Cannot connect to the Docker daemon at unix:///var/run/docker.sock | The Docker service is not running; often there is a syntax error in daemon.json | Read the cause with systemctl status docker and journalctl -u docker -n 50, and check the file with dockerd --validate |
permission denied while trying to connect to the Docker daemon socket | The user is not in the docker group, or the membership has not reached the open session yet | Use sudo or log out and back in; look for the docker group in the output of id |
docker: 'compose' is not a docker command | The Compose plugin is not installed | Install the docker-compose-plugin package, and use docker compose instead of the old hyphenated docker-compose (v1) |
Conflicting values set for option Signed-By | The Docker repository is defined in two files with different key paths | Delete the old Docker entry under /etc/apt/sources.list.d/ and run apt-get update |
bind: address already in use | Another process is using the host port (e.g. Nginx on 80) | Find the process with ss -ltnp 'sport = :80' and choose a different host port |
connect() to 127.0.0.1:8080 failed (13: Permission denied) | On AlmaLinux, SELinux is blocking Nginx from making network connections | setsebool -P httpd_can_network_connect 1 |
toomanyrequests (pull rate limit) | Docker Hub's download limit for users who are not signed in | Sign in with docker login and cut down on unnecessary pull loops |
Frequently asked questions
Can I use UFW and Docker together?
Yes. UFW keeps protecting services that run directly on the server, such as SSH and Nginx; it just cannot control the ports Docker publishes. If you publish containers on 127.0.0.1 and provide outside access through Nginx, the two tools work side by side without conflict.
Should I use the Docker snap on Ubuntu?
The snap package is not the installation method Docker documents; it keeps its files in different directories, and because of snap confinement some bind mount paths may not work as expected. Use the official repository so the paths in this guide apply, and do not keep both installations at the same time.
Do containers start automatically after the server restarts?
They do if the Docker service is enabled at boot and the container has the restart: unless-stopped or always policy. A container you stopped manually with docker compose stop stays stopped after a restart under the unless-stopped policy.
How many resources does Docker need?
The Engine itself uses little; your containers determine what you need. For projects with a database, prioritize RAM and watch usage with docker stats. When choosing a package, the resource selection guide can help.
Related articles
Thanks for your feedback!