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.
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.
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:
- IPv6 address:
The following routed subnets have been created and are being routed to the servers primary IPs:
Creating the Docker bridge network
my-net using our routed IPv4 and IPv6 networks
$ docker network create \ --ipv6 \ --driver='bridge' \ --subnet=188.8.131.52/29 \ --gateway=184.108.40.206 \ --subnet=2a00:9080:9:69::/64 \ --gateway=2a00:9080:9:69::1 \ my-net
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.
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=220.127.116.11 \ --ip6=2a00:9080:9:69::4 \ nginx:latest