访问虚拟机网站失败----防火墙
问题:CentOS宿主机无法访问虚拟机中的web服务?
原因:因为CentOS 的防火墙没有开通web服务的 port 端口,屏蔽了外部的访问。
解决方法:
有两种方法可以使宿主机能够访问虚拟机的网页:
(1)关闭虚拟机中的防火墙;(2)打开web服务的80端口
查看Linux环境
[root@localhost ~]# cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)
[root@localhost ~]# uname -a
Linux localhost.localdomain 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
CentOS6 中方案
关闭防火墙
service iptables stop
命令可以临时关闭防火墙,这样就可以通过宿主机访问虚拟机中的网页了。
iptables 防火墙一般是开机启动的,使用上面的命令临时关闭了防火墙后,下次开机还是会启动防火墙软件,可以使用如下命令禁止开机启动防火墙:chkconfig iptables off
但是,防火墙的目的就是为了防止外部的恶意访问的,所以最好还是保持防火墙的运行。
- 开启相应的端口
2.1、命令行方式开启80端口
使用如下命令可以临时开启80端口:/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT
重启防火墙即可生效:service iptables restart
如果要保持80端口在下次开机时仍然是开启状态,那么使用如下命令保存当前的设置:service iptables save
2.2、修改iptables的配置文件来开启端口
vim /etc/sysconfig/iptables
命令修改 iptables 防火墙配置文件,添加一行内容如下:
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
然后重启防火墙:service iptables restart
这样就可以通过宿主机访问虚拟机的网络服务了。
CentOS7 中方案
#防火墙命令快速预览
systemctl status firewalld.service #查询防火墙状态
systemctl start firewalld.service #打开防火墙状态
systemctl stop firewalld.service #关闭防火墙状态
systemctl disable firewalld.service #设置开机关闭防火墙
- 查看已经开放的端口: firewall-cmd --list-ports
- 开启端口:firewall-cmd --zone=public --add-port=80/tcp --permanent
- 关闭端口:firewall-cmd --zone=public --remove-port=80/tcp --permanent
命令含义:
–zone #作用域
–add-port=80/tcp #添加端口,格式为:端口/通讯协议
–permanent #永久生效,没有此参数重启后失效
- 重启防火墙:firewall-cmd --reload
- 查看默认防火墙状态(关闭后显示notrunning,开启后显示running):firewall-cmd --state
- 关闭防火墙
1 ) 永久性生效,重启后不会复原
开启: systemctl enable firewalld
关闭: systemctl disable firewalld
2 ) 即时生效,重启后复原
开启: systemctl start firewalld
关闭: systemctl stop firewalld - 检查配置正确性:firewall-cmd --check-config
- 重新加载防火墙配置:firewall-cmd --reload
firewall-cmd --list-ports #查看当前已开放端口
#其中 public表示[作用域] 84/tcp 表示[端口和访问类型] --permanent[永久生效]
firewall-cmd --permanent --zone=public --add-port=84/tcp #开启TCP 84端口
firewall-cmd --permanent --zone=public --remove-port=84/tcp #关闭TCP 84端口
firewall-cmd --check-config #检查配置正确性
firewall-cmd --reload #重新加载防火墙配置(前面的84端口才会生效)