Docker Containers with Public IPs

If you need to assign public routable IP addresses directly to each individual Docker containers, using routed networks will greatly simplify your configuration.

Why routed networks?

By routing a network directly to your server, allows you full control over address assignments and segmentation within the network as well as mobility as it can easily be routed to a new destination if needed.

Full control

It is especially useful when running virtual machines or containerized applications that need public addressing, as it both simplifies your configuration and allows you full control over address assignment of your applications.

When a routed network prefix is routed to a server or a network device, it can be subnetted into smaller networks allowing you to create multiple networks from the prefix, inside the host or hypervisor.

Increased mobility

Routed networks are defined by a network prefix and a next-hop address. The next-hop is the servers primary IP address. By changing the next-hop a whole network can easily be moved between servers.

Creating a network

In this example, we have a bare-metal server where we want to provide publicly routable IPv4 and IPv6 addresses. The server has been assigned the following primary public addresses:

  • IPv4 address: 82.103.187.2/20
  • IPv6 address: 2a00:9080:9:187::1/64

The following routed subnets have been created and are being routed to the servers primary IPs:

  • 82.103.188.0/29
  • 2a00:9080:9:69::/64

Creating the Docker bridge network my-net using our routed IPv4 and IPv6 networks 82.103.188.0/29 and 2a00:9080:9:69::/64.

$ docker network create \
    --ipv6 \
    --driver='bridge' \
    --subnet=82.103.188.0/29 \
    --gateway=82.103.188.1 \
    --subnet=2a00:9080:9:69::/64 \
    --gateway=2a00:9080:9:69::1 \
    my-net

Note

We will configure the first usable address of each prefix as the gateway. Docker assigns the gateway IP address to the bridge interface on the host. Docker containers using the my-net network will use this IP as their default gateway to reach the Internet.

Creating containers

When starting a container and specifying the my-net network, Docker will automatically assign an available address from the network to the container. On Docker networks with both IPv4 and IPv6, one of each address family will be assigned to the container.

Example of creating a new container, specifying the my-net network created above:

$ docker run -d --name my-nginx --network my-net nginx:latest

Assuming you want to directly assign a specific IPv4 and IPv6 address to the container:

$ docker run -d \
    --name=my-other-nginx \
    --network=my-net \
    --ip=82.103.188.4 \
    --ip6=2a00:9080:9:69::4 \
    nginx:latest