How Can I Set a Static IP Address for My Docker Containers Using Docker Compose?

0
6
Asked By CuriousCactus42 On

I manage all my Docker containers under a network named "cloudflared". Recently, one of my containers stopped working, and when I restarted it, it received a new IP address in the cloudflared network. This change messed up my Cloudflare tunnel configurations, as my subdomains shifted with the new IP. I want to avoid needing to update the IP in my Cloudflare dashboard every time this happens, so I'm looking for a way to assign a static IP to each container directly in my docker-compose file. I'm still learning Docker, so I'd appreciate a clear explanation on how to do this. Below is my current docker-compose configuration for one service. Can someone show me where and how to define a static IP?

```yaml
services:
whoami:
container_name: simple-service
image: traefik/whoami
networks:
- cloudflared

networks:
cloudflared:
name: cloudflared
```

1 Answer

Answered By DockerDude123 On

You can assign static IPs by defining the IP address for each service directly in your docker-compose file. Just like how you mentioned, you need to add the `ipv4_address` field under the service that you want to have a static IP. Here's a modified version of your `docker-compose.yml`:

```yaml
version: '3.8'

networks:
cloudflared:
driver: bridge
ipam:
config:
- subnet: 172.18.0.0/16 # Make sure this matches your inspected network settings

services:
whoami:
container_name: simple-service
image: traefik/whoami
networks:
cloudflared:
ipv4_address: 172.18.0.10 # Assign a specific static IP here
# Add other services similarly
```
Just be careful with IP conflicts! You'll have to manually check to ensure that no two containers get the same static IP.

NewbieNora -

Thanks for breaking it down! So, if I understand correctly, I have to ensure that the IP I assign is unique within that subnet. Got it!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.