Jesse Nelson
Jesse Nelson

Reputation: 796

Add additional IPs to lo interface in docker container

I need to setup aliases on the loopback(lo) interface in my docker container. I can't figure out how to do this in the docker-compose file.

I need to add 127.0.0.2, 127.0.0.3, and 127.0.0.4 to the lo interface. How can this be done in the docker-compose file?

On my mac I could just do something like ifconfig lo0 alias 127.0.0.4 up but I can't figure out how to get this done in a docker container.

Upvotes: 2

Views: 2731

Answers (1)

Matt
Matt

Reputation: 74831

Firstly, linux will respond to 127.0.0.2-4 by default as 127.0.0.1/8 is assigned to the lo interface. You may not need to "add" the addresses to the interface, just use them.

If for some reason you need the specific address on the interface, then it requires getting into the internals of Docker networking. There is a utility called pipework that deals with this type of thing and these steps are lifted from it's code.

Get the PID of the container

NSPID=$(docker inspect -f '{{ .State.Pid }}' <container>)

Let ip netns work for this container

mkdir -p /var/run/netns
rm -f "/var/run/netns/$NSPID"
ln -s "/proc/$NSPID/ns/net" "/var/run/netns/$NSPID"

Add the IP address to the interface

ip netns exec $NSPID ip ad add 127.0.0.2/32 dev lo

Confirm the new config is there

ip netns exec $NSPID ip ad sh lo

This allows you to make any changes in the containers network namespace.

Upvotes: 2

Related Questions