When a Docker container starts up, it gets a dynamic IP address by default. In this article, we will show you how to assign a static IP address to a specific Docker container.
Create a new Docker network:
$ docker network create --subnet=172.11.0.0/16 mycustomnetwork
You can run a docker container in this network with a specific (static) IP address:
$ docker run --net customnetwork --ip 172.11.0.11 -d container
To find out the current IP address assigned to the Docker container, run the command:
$ docker container inspect -f '{{ .NetworkSettings.IPAddress }}' CONTAINER_ID_OR_NAME
You can also set a static IP address in the docker-compose.yml file using the ipv4_address directive. For example:
$ sudo vim docker-compose.yml
version: '2'
services:
webserver:
image: nginx
ports:
- '8282:80'
container_name: web-server
networks:
customnetwork:
ipv4_address: 172.12.0.11
networks:
mycustomnetwork2:
ipam:
config:
- subnet: 172.12.0.0/16