docker,

Assign static IP to a Docker container

Oct 24, 2021 · 1 min read · Post a comment

There are two types of static IPs, public and private IP addresses. We all know the public IP Docker mapping by now, using Nginx and port mapping. Today we are going to see how can we assign a private IP address to a Docker container.

Prerequisites

  • Docker

Using Docker Compose

version: "3.8"

services:
  app:
    image: nginx:alpine
    networks:
      frontend_network:
        ipv4_address: 172.16.100.11

networks:
  frontend_network:
    ipam:
      driver: default
      config:
        - subnet: "172.16.100.0/24"

Using Docker CLI

Step 1. Create a network first.

docker network create --subnet=172.16.100.0/24 frontend_network

Step 2. Spin up a container.

docker run --net frontend_network --ip 172.16.100.11 -dit test_container

Step 3. Verify the IP address assignment.


docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' test_container

Conclusion

Using a private static IP address for a Docker container is not a good practice at all, but it could help you with debugging a local development environment stack. Although this is a hack around, always make sure to use the service name as part of the service endpoint reference.
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.