CodeBlanks Logo Icon CodeBlanks

IP binding

Learn to bind a port to a specific IP.

IP binding

By default -p 5432:5432 listens on all interfaces (0.0.0.0); on a server this means opening the database to the internet. For access only from the same machine, it is bound to the IP 127.0.0.1:

docker run -d -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD=gizli postgres:16
$ docker port <id>
5432/tcp -> 127.0.0.1:5432

Careful: Docker adds firewall rules itself to publish ports; tools like ufw don't always block these ports.

Not publishing at all

The safest option is often not publishing the port at all. Containers on the same Docker network can reach each other without publishing ports (you'll see this in the network group). Only the service that really must be reached from outside (e.g. a reverse proxy) is published:

docker network create arka
docker run -d --name db --network arka postgres:16          # no publishing
docker run -d --name web --network arka -p 80:80 nginx       # only web

Practice A safe Redis

Start a container named cache from redis:7 in the background; publish port 6379 with the same number only on the host's 127.0.0.1 address.

Starter code

terminal
# buraya yaz

Expected output

f6a7b8c9d0e1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which opens a database on a server only to applications on that server?

  • -p 0.0.0.0:5432:5432
  • -P
  • -p 127.0.0.1:5432:5432 Correct answer
  • -p 5432:5432

Explanation: 127.0.0.1 accepts only local connections.

2 Bind the port only to the local interface.

Question
docker run -d -p ____:6379:6379 redis
Answer
docker run -d -p 127.0.0.1:6379:6379 redis

Explanation: 127.0.0.1 is the local loopback interface.

3 Match.

Term Meaning
0.0.0.0 All interfaces
127.0.0.1 Local only
no publish Only from inside the network
ufw Doesn't always block Docker rules

All lessons in Beginner