本来docker run -p就是一条iptables规则

一、运行一个带有ssh的容器

[root@centos7 alpine-ssh]# docker run --name alipne-ssh -d   alpine-ssh:3.13

二、宿主机上使用容器ip连接测试,没毛病

[root@centos7 alpine-ssh]# docker inspect --format='{{.NetworkSettings.IPAddress}}' alipne-ssh
172.17.0.2
[root@centos7 alpine-ssh]# ssh [email protected] -p22
The authenticity of host '172.17.0.2 (172.17.0.2)' can't be established.
ECDSA key fingerprint is SHA256:cZNrualIfoTpoDrhaeJnvrNTgAWL8Ijfz7VFGk/dXgI.
ECDSA key fingerprint is MD5:64:6a:90:bf:80:aa:84:27:c5:95:06:76:9c:81:c2:fa.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.17.0.2' (ECDSA) to the list of known hosts.
[email protected]'s password: 
Welcome to Alpine!

The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org/>.

You can setup the system with the command: setup-alpine

You may change this message by editing /etc/motd.

58c172a628ae:~#

三、添加一条iptables规则

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 3022 -j DNAT --to-destination  172.17.0.2:22

四、xshell连接测试

[root@ubuntu ~]$ ssh [email protected] -p3022
[email protected]'s password: 
Welcome to Alpine!

The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org/>.

You can setup the system with the command: setup-alpine

You may change this message by editing /etc/motd.

58c172a628ae:~#