在 docker-compose 容器中找不到 iptables 命令

iptables command not found in docker-compose container

我们有 docker-compose 文件

version: '3'
services:
    prometheus-server:
        image: prom/prometheus
        ports:
            - 9090:9090
        volumes:
            - ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml

    grafana-ui:
        privileged: true
        image: grafana/grafana-oss:latest
        ports:
            - 3000:3000
        environment:
            - GF_SECURITY_ADMIN_PASSWORD=secret
        links:
            - prometheus-server:prometheus
        cap_add:
            - NET_RAW
            - NET_ADMIN

然而,/bin/sh: iptables: not found当我们试图运行通过iptables -nvL -t nat通过docker exec -it <grafana-ui container id> /bin/sh。我有什么想念的吗?如何在docker容器中运行iptables

根据这个问题,添加了参数--cap-add=NET_ADMIN--cap-add=NET_RAW,但是,我运行iptables也没有。

/bin/sh: iptables: not found

这意味着 grafana/grafana-oss:latest 默认不包含 iptables 命令。

您可以使用 apk add --no-cache iptables ip6tables 安装它,请参阅 Running (and debugging) iptables inside a Docker container

接下来的快速实验:

nxa13855@shlava:~$ docker run --entrypoint /bin/bash -idt --cap-add=NET_ADMIN --cap-add=NET_RAW grafana/grafana-oss:latest
21296933a1d59c45c68c8ab1120b4324b717aea8d220ca070c2c8f21c449e6a5
nxa13855@shlava:~$ docker ps
CONTAINER ID   IMAGE                        COMMAND                  CREATED         STATUS         PORTS                    NAMES
21296933a1d5   grafana/grafana-oss:latest   "/bin/bash"              8 seconds ago   Up 7 seconds   3000/tcp                 awesome_villani
nxa13855@shlava:~$ docker exec -uroot -it 21296933a1d5 /bin/bash
bash-5.1# apk add --no-cache iptables ip6tables
fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/main/x86_64/APKINDEX.tar.gz
fetch https://dl-cdn.alpinelinux.org/alpine/v3.14/community/x86_64/APKINDEX.tar.gz
(1/4) Installing libmnl (1.0.4-r1)
(2/4) Installing libnftnl-libs (1.2.0-r0)
(3/4) Installing iptables (1.8.7-r1)
(4/4) Installing ip6tables (1.8.7-r1)
Executing busybox-1.33.1-r6.trigger
Executing glibc-bin-2.30-r0.trigger
/usr/glibc-compat/sbin/ldconfig: /usr/glibc-compat/lib/ld-linux-x86-64.so.2 is not a symbolic link

OK: 29 MiB in 38 packages
bash-5.1# iptables -nvL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
bash-5.1#

对于你来说,你可能需要写你的所有者 dockerfile extends from grafana/grafana-oss:latest,在那个 dockerfile 中,添加 apk add --no-cache iptables ip6tables 让你的镜像默认有 iptables 命令。

如果只是为了调试,你可以像我上面那样直接执行到那个容器来安装命令,但记得在 exec 时添加 -uroot 因为该图像默认不使用 root.