Assign Static IP to Container with Docker Compose

Introduction

When we run a Docker container, it connects with a virtual network using an IP address. For this reason, we expect services to get a configuration dynamically. However, we might want to use a static IP instead of an automatic IP allocation.

Docker runs its own DNS services that allows communication inside a network via name resolution. This is usually adequate but I recently had a requirement for one container in a stack to have a static IP so that other containers (with config files) could communicate.

Create a Docker Network with subnet

docker network create --driver=bridge --subnet=10.10.10.0/24 --gateway=10.10.10.1 my_network

This command manually creates a Docker network called "my_network" with a network address range 10.10.10.2 - 10.10.10.254, a subnet mask of 255.255.255.0 and a default gateway of 10.10.10.1.

The Docker Compose File

---
version: "3.8"

services:
  filebrowser:
    image: hurlenko/filebrowser:latest
    container_name: filebrowser
    hostname: filebrowser
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    environment:
      - TZ=Europe/Stockholm
      - PUID=1000
      - PGID=1000
    ports:
      - 8080:8080
    volumes:
      - /opt/filebrowser/config:/config
      - /:/data
      - /etc/localtime:/etc/localtime:ro
    networks:
      my_network:
        ipv4_address: 10.10.10.2
    labels:
      - com.centurylinklabs.watchtower.enable=true

networks:
  my_network:
    external: true

docker-compose.yml

This compose file creates a container and joins it to the existing "my_network" Docker network and assigns it a static IP address of 10.10.10.2.