最近使用frp做跳板遠程運維內網的服務器,盡管已經屏蔽了海外IP對vps服務器的訪問,但是總覺得直接暴露遠程管理的端口在互聯網上還是不安全。於是想着用Ocserv做服務端先vpn撥進去在進行運維會安全很多。選擇Ocserv的原因也是因為支持思科的anyconnect
客戶端,各大應用市場都不屏蔽比較具有易用性。
然而在Centos8上安裝Docker之后,Docker中再使用Ocserv容器的時候iptables不能正常工作。目前貌似資料不好找,特此做個筆記保留下。
故障描述
附上Docker-Ocserv作者Git:https://github.com/Pezhvak/docker-ocserv
我很喜歡這個封裝好的Docker image,當然為了適配也做了一些更改,其中也包括了下文。
該Docker鏡像使用非常小巧的 Alpine Linux,由於VPN撥號之后需要做NAT才可以訪問其他網絡中地址,結果抓包看到不正常。進入容器中提示如下。
iptables -L -n
modprobe: can't change directory to '/lib/modules': No such file or directory
iptables v1.8.7 (legacy): can't initialize iptables table `filter': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
作為關鍵詞問搜索引擎之后得到的大多答案有兩個解決問題的方法:
-
修改Docker容器的權限:給
--privileged
權限。或者擔心權限過大限定特定權限:--cap-add NET_ADMIN --cap-add NET_RAW
。我已經給了最大的--privileged
權限還是無效。 -
提示的錯誤信息很明確,找不到對應的內核模塊,讓容器加載iptables相關內核模塊。但是這個方法實際是不靠譜的,因為容器和宿主機共享內核。
於是在搜索了一些相關項目的issues帖子之后找到了根本解決的方法。
文中有人提到:發現宿主機是Centos8
,並且容器為alpine:3.10
的時候出現了相同問題。原因是Centos8
沒有加載iptables需要的內核模塊。該作者通過先執行:sudo modprobe iptable_filter
,sudo modprobe iptable_nat
之后再開啟alpine
容器修復了這個問題。
我在想:我的宿主機Centos8
運行的Iptables工作良好呀,怎么可能沒有加載iptables所需要的內核模塊呢?
再接下來的回帖中找到了答案:原來再存在兩個版本的iptables,他們分別是iptables-nft
和iptables-legacy
這兩個iptables使用了不同的內核模塊。alpine
默認使用的是iptables-legacy
而Centos8
默認使用的是iptables-nft
。因為宿主機沒有加載對應的內核模塊所以容器就無法使用內核模塊就說得過去了。
解決問題:
那么現在解決問題的方法有兩個了,一個是參照文中提到的手動加載容器中iptables-legacy
所需的模塊(該方法我並未驗證使用,擔心對宿主機中已經配置好的iptables產生影響)。
第二個方法也是我在用的方法,將容器啟動腳本中所有的iptables
命令,更改為iptables-nft
問題完美解決。
iptables-nft -L -n
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
# 例如:
iptables-nft -t nat -A POSTROUTING -j MASQUERADE
iptables-nft -A INPUT -p tcp --dport 443 -j ACCEPT
iptables-nft -A INPUT -p udp --dport 443 -j ACCEPT
相關鏈接:
https://blog.csdn.net/dog250/article/details/54170683
https://github.com/kylemanna/docker-openvpn/issues/564
https://github.com/qdm12/gluetun/issues/896
https://github.com/moby/moby/issues/18230