CentOS7 LXC网络以及配置

安装EPEL源.

yum install epel-release.noarch -y

禁用Firewalld使用iptable代替.

systemctl stop firewalld
systemctl disable firewalld
yum install iptables iptables-services net-tools -y

创建iptables默认规则.

echo "# sample configuration for iptables service
# you can edit this manually or use system-config-firewall
# please do not ask us to add additional ports/services to this default configuration
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT" > /etc/sysconfig/iptables;
systemctl enable iptables.service
systemctl start iptables.service

安装Linux Container.

yum install lxc lxc-templates -y

为容器设置虚拟交换机.

echo 'DEVICE="virbr0"
ONBOOT="yes"
TYPE="Bridge"
BOOTPROTO=static
IPADDR=10.0.0.1
NETMASK=255.255.255.0' > /etc/sysconfig/network-scripts/ifcfg-lxcbr0;

启用内核转发以及虚拟内存调整.

echo "net.ipv4.ip_forward = 1
vm.swappiness = 10
net.ipv4.tcp_timestamps = 0" >> /etc/sysctl.conf;
sysctl -p

设置iptables nat.

iptables --flush POSTROUTING --table nat
iptables --flush FORWARD
iptables -t nat -A POSTROUTING -o 网卡 -j MASQUERADE
iptables-save > /etc/sysconfig/iptables

应用相关服务.

systemctl start lxc
systemctl enable lxc
systemctl restart network

Q&A

  • Q: 容器启动后一直持续占用CPU.

  • A: 编辑/var/lib/lxc/{container}/config加入:

    lxc.autodev = 1
    lxc.kmsg = 0
    
  • Q: 容器设置静态IP.

  • A:编辑/var/lib/lxc/{container}/config加入:

  • lxc.network.type = veth
    lxc.network.link = virbr0
    lxc.network.flags = up
    lxc.network.name = eth0
    lxc.network.ipv4 = 10.0.0.2/24
    lxc.network.ipv4.gateway = 10.0.0.1
    

常用命令

# 创建指定版本的容器
lxc-create -n centos -t mcentos -- --release 6

# 当目标IP为192.168.0.160且端口为2222 NAT 10.0.0.2:22 
iptables -t nat -A PREROUTING -d 192.168.0.160 -p tcp --dport 2222 -j DNAT --to 10.0.0.2:22

# 当目标网口为ens160且端口为2222时 NAT 10.0.0.2:22
iptables -t nat -A PREROUTING -i ens160 -p tcp --dport 2222 -j DNAT --to-destination 10.0.0.2:22

# 当任意网口目标端口为2222时 NAT 10.0.0.2:22
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 10.0.0.2:22

# 当目任意网口标端口为2222~4444 NAT 10.0.0.2:2222~4444
iptables -t nat -A PREROUTING -p tcp --dport 2222:4444 -j DNAT --to-destination 10.0.0.2:2222-4444

# 为ens160网口增加一个ip
ifconfig ens160 add 192.168.0.161

# 为ens160网口删除一个ip
ifconfig ens160 del 192.168.0.161

# DMZ
iptables -t nat -A PREROUTING -d 192.168.0.161 -j DNAT --to 10.0.0.2

# 删除DMZ
iptables -t nat -D PREROUTING -d 192.168.0.161 -j DNAT --to 10.0.0.2

# 限速 1m上 2m下
wondershaper ens160 1024 2048

# 解除限速
wondershaper clear ens160

标签: none

仅有一条评论

  1. srar的脑残粉 srar的脑残粉

    支持一下,很好

添加新评论