Macvlan in docker is a networking driver which allows you to
create multiple virtual network interfaces (i.e.,MAC addresses)
on a single physical network interface. And we can connect
each of these virtual interfaces to a Docker container which
gives each container its own unique network identity on the
same physical network on which host IP is running. Macvlan
is very useful when you want to assign each container a
unique IP address on your network, making them appear as if
they are individual physical devices. And sometimes is also
useful when you want to connect it to outside world.
Below are the steps used to create and use MacVLAN with docker
container:
Step1: Create a Macvlan network:
If you want to run containers on your desired network then you
need to create a network before you can attach containers to
it. Here we are creating a MacVLAN netowkr and ens192 is the
physical network interface on your host machine.
# docker network create -d macvlan -o parent=ens192 macvlan_test
You must replace ens192 with the actual name of your physical
network interface, which you can find by running the ifconfig
or ip a command.
# docker network ls (You can see your newly created network)
Step2: Start a container and attached to the Macvlan network
you have created:
Specify the --network flag with the name of your Macvlan
network when running the container.
# docker run -d --name container_test --network macvlan_test nginx
This command creates a Docker container named "container_test"
running the Nginx web server, and it's connected to the
"macvlan_test" Macvlan network.
You can also assign a static IP address to the container while
running a container if you know your network (optional):
By default, Macvlan assigns IP addresses from your physical
network's DHCP server if you have. If you want to assign a
static IP address to the container, you can do so when starting
the container using the --ip flag:
# docker run -d --name container_test --network macvlan_test --ip 192.168.68.21 nginx
Replace 192.168.68.21 with the desired static IP address.
Step3: Now you can verify connectivity:
You can test the connectivity of your container by running
commands like ping or curl from within the container to access
resources on your network or the internet.
# docker exec -it container_test ping google.com
This will execute the ping command inside the my_container
container.
Remember that Macvlan networking is little bit complex to set
up than the default bridge network as it requires certain
configurations on your physical network as well. You need to
ensure that your network infrastructure supports Macvlan and
that you have the necessary permissions to create Macvlan
networks on your Docker host.
Like you need to enable promiscuous mode on host using command:
# ip link set ens192 promisc on