How to Set a Specific Static IP Address for a Docker Container in Ubuntu Linux

Why Use a Static IP for a Docker Container?

By default, when you launch a Docker container in Ubuntu, the Docker daemon automatically assigns it an IP address from the default bridge network pool. If the container is restarted, recreated, or if the host machine reboots, this assigned IP address can change. For most web applications, this dynamic assignment is fine because services communicate via container names. However, if you are running legacy software, configuring strict firewall rules, setting up local DNS servers (like Pi-hole), or integrating the container with external network devices, a changing IP address will break your configuration. In these specific scenarios, you must assign a static IP address to ensure the container always boots with the exact same network identity.

Step 1: Create a Custom Docker Network

You cannot assign static IP addresses to containers using the default Docker bridge network. You must first create a user-defined custom network and specify its subnet.

  1. Open your Terminal in Ubuntu.
  2. Run the following command to create a new bridge network (we will name it my_custom_network and assign it a subnet of 172.20.0.0/16):
  3. sudo docker network create --subnet=172.20.0.0/16 my_custom_network
  4. Verify the network was created successfully by listing your networks:
  5. sudo docker network ls

Step 2: Assign the Static IP During Container Creation

Now that you have a custom network with a defined subnet, you can assign a specific static IP address from that subnet when you create and run a new container.

  1. Use the --net flag to specify your custom network, and the --ip flag to assign the specific address. For example, to run an Nginx container with the static IP 172.20.0.10, use this command:
  2. sudo docker run -d --net my_custom_network --ip 172.20.0.10 --name static_nginx nginx

Step 3: Assigning a Static IP Using Docker Compose

If you manage your containers using Docker Compose (which is highly recommended for complex setups), you can define the static IP directly within your docker-compose.yml file.

  1. Open your docker-compose.yml file in a text editor.
  2. Define the custom network and specify the static IP under the service configuration:
version: '3'
services:
  web:
    image: nginx
    networks:
      custom_net:
        ipv4_address: 172.20.0.10

networks:
  custom_net:
    driver: bridge
    ipam:
      config:
        - subnet: 172.20.0.0/16

By using either the CLI flags or a Compose file, the Docker container will now reliably boot with the exact same IP address every time it starts.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.