Skip to content

Instantly share code, notes, and snippets.

@vishvananda
Last active January 8, 2022 18:21
Show Gist options
  • Save vishvananda/5834761 to your computer and use it in GitHub Desktop.
Save vishvananda/5834761 to your computer and use it in GitHub Desktop.
Expose the netns of a docker container to the host.
#!/usr/bin/env bash
if [ "$1" == "" ]; then
echo "usage: $0 <docker_id>"
echo "Exposes the netns of a docker container to the host"
exit 1
fi
ppid=`docker inspect $1 | grep Pid | awk '{print $2 + 0}'`
if [ "$ppid" == "" ]; then
echo "lxc parent pid not found"
exit 1
fi
pid=`ps --ppid $ppid -o pid | tail -n1`
if [ "$pid" == "" ]; then
echo "lxc child pid not found"
exit 1
fi
sudo mkdir -p /var/run/netns
sudo rm -f /var/run/netns/$1
sudo ln -s /proc/$pid/ns/net /var/run/netns/$1
echo "Container netns exposed as $1"
echo "For example try: sudo ip netns exec $1 ip addr"
@kaharlichenko
Copy link

You could extract the pid of the container with docker inspect directly without any grep/awk magic:

ppid=$(docker inspect --format '{{.State.Pid}}' $1)

Also, why do you query for any child processes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment