Year-end offer: 30% off your first 6 months. Order by 31 December.

Run Docker containers safely on Ubuntu and Debian without opening extra ports

Docker makes self-hosting apps easy, yet it brings one surprise that catches many Ubuntu and Debian server owners: publishing a container port punches straight through UFW by default. Here is how to keep internal app ports closed to the internet and harden your containers.

Short version: bind published Docker ports to 127.0.0.1 (for example 127.0.0.1:8080:8080) behind Nginx, never mount /var/run/docker.sock unless strictly needed, and run containers as a non-root user.

1. Stop Docker from bypassing UFW

When you write -p 8080:8080 (or ports: ["8080:8080"] in compose.yml), Docker listens on every public IP address and adds iptables rules ahead of UFW. Even if sudo ufw status only shows ports 22, 80, and 443, anyone on the internet can reach port 8080 directly without HTTPS.

Always bind internal web apps, Redis, and admin tools to localhost only:

ports:
  - "127.0.0.1:8080:8080"

Then point Nginx on the host at http://127.0.0.1:8080 with HTTPS and rate limits. Afterwards, verify from the host with our open ports check on Ubuntu and Debian and keep UFW firewall rules tight.

2. Never expose the Docker socket lightly

Some container tools ask you to mount /var/run/docker.sock:/var/run/docker.sock. Keep in mind what that means: any process inside that container can start a privileged container that reads or modifies every file on your host server as root. Avoid mounting docker.sock into any internet-facing web app or dashboard.

3. Run containers without root privileges inside

By default, many containers run as root inside the container. In compose.yml, drop unnecessary Linux capabilities and block privilege escalation for app containers:

services:
  app:
    image: your-app:1.4.2
    user: "1000:1000"
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    ports:
      - "127.0.0.1:8080:8080"

Test on a staging container first so your mounted data folder permissions match user 1000:1000 cleanly.

4. Keep base images and host OS patched

Updating Ubuntu packages with apt updates the host kernel and Docker engine, not the software packaged inside your running Docker images. Pull updated image tags regularly and recreate containers cleanly:

docker compose pull
docker compose up -d --remove-orphans
docker image prune -f

And make sure your host stays up to date automatically using our guide on automatic security updates on Ubuntu and Debian.

← Back to the security blog