Table of Contents
Introduction
In some cases, users want their containers and application to lease IP addresses from their home network. However, the home router it is already pre-configured with a DHCP server to hand out configuration to the computers and other devices. Depending on your situation, the possible solution is to use the macvlan and dhcp plugins include in the containernetworking-plugins. This solution only applies to rootfull containers.
Creating a CNI with macvlan
The macvlan creates a virtual copy of a master interface and assigns the copy a randomly generated MAC address. The pod can communicate with the network that is attached to the master interface.
According this help the command to create this new container network interface using the host interface eth0:
sudo podman network create --macvlan eth0 newnet
The other important field is the network name; in this case, it is newnet. So after this command executed, we can see a new file in the directory.
sudo cat /etc/cni/net.d/newnet.conflist
{
"cniVersion": "0.4.0",
"name": "newnet",
"plugins": [
{
"type": "macvlan",
"master": "eth0",
"ipam": {
"type": "dhcp"
}
}
]
Running the DHCP plugin
As seen above, macvlan and dhcp contain network plugins that work together. The dhcp plugin is a DHCP proxy client for the container because most container images lack a DHCP client to interact with a DHCP server.
First to test you can execute the plugin, run it:
sudo /usr/libexec/cni/dhcp daemon &
Before to continu, consider the following example to run an Alpine container and checking the IP address of the network interface.
sudo podman run -it --rm --network newnet alpine ip addr show eth0
2: eth0@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether f6:dd:1b:a7:9b:92 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.22/24 brd 192.168.1.255 scope global eth0
...
In the example, the eth0 interface for the container leases an IP address of 192.168.1.22 and the host network is 192.168.1.0/24.
Creating service
Let’s go to automating this procedure with systemd. You simply need a socket and service file.
The socket file is as follows:
vi /usr/lib/systemd/system/io.podman.dhcp.socket
[Unit]
Description=DHCP Client for CNI
[Socket]
ListenStream=%t/cni/dhcp.sock
SocketMode=0600
[Install]
WantedBy=sockets.target
And the service file:
/usr/lib/systemd/system/io.podman.dhcp.service
[Unit]
Description=DHCP Client CNI Service
Requires=io.podman.dhcp.socket
After=io.podman.dhcp.socket
[Service]
Type=simple
ExecStart=/usr/libexec/cni/dhcp daemon
TimeoutStopSec=30
KillMode=process
[Install]
WantedBy=multi-user.target
Also=io.podman.dhcp.socket
You only need to enable and start the socket
sudo systemctl --now enable io.podman.dhcp.socket
Thank you for the initial photo.
Photo by Denys Nevozhai on Unsplash