tl;dr
firewall-cmd --permanent --zone=public --add-port=2888/tcp
firewall-cmd --reload #重新載入服務
永久配置firewalld開啟端口。
之前的一些坑
之前的一篇文章CentOS 7部署Node.js+MongoDB:在VPS上從安裝到Hello world中,講到了CentOS開啟端口用這個命令
firewall-cmd --add-port=3000/tcp
這樣是沒錯,開啟了端口,但是后面發現這個端口會莫名其妙的被關閉
Google一番后了解到這樣添加端口是運行時配置(Runtime configuration),在重載或重啟firewalld后,這個配置就失效了。
自動關閉原因
CentOS 7 采用了firewalld作為防火墻服務,在Red Hat官方文檔的Security Guide中有介紹firewalld
The dynamic firewall daemon firewalld provides a dynamically managed firewall with support for network “zones” to assign a level of trust to a network and its associated connections and interfaces. It has support for IPv4 and IPv6 firewall settings. It supports Ethernet bridges and has a separation of runtime and permanent configuration options. It also has an interface for services or applications to add firewall rules directly.
動態防火墻守護進程firewalld提供一個動態管理的防火墻,支持網絡“區域”(zones),以用來給一個網絡以及其關聯的鏈接和接口分配一個信任層級。firewalld支持IPv4跟IPv6的防火墻設置。它還支持以太網橋,并且有運行時配置選項跟永久配置選項(runtime and permanent configuration options),二者相互分離。并且firewalld為服務或應用直接添加防火墻規則提供了接口。
有關Network Zones的概念這邊不細講,參照Security Guide。
firewalld有個圖形化配置工具firewall-config,還有個命令行客戶端,就是firewall-cmd了。
我們暫時還沒用到圖形化工具,所以這邊就說一下firewall-cmd
Security Guide中關于firewall-cmd的介紹:
A command line client, firewall-cmd, is provided. It can be used to make permanent and non-permanent runtime changes as explained in man firewall-cmd(1). Permanent changes need to be made as explained in the firewalld(1) man page. Note that the firewall-cmd command can be run by the root user and also by an administrative user, in other words, a member of the wheel group. In the latter case the command will be authorized via the polkit mechanism.
具體就不翻譯了,大概是說
firewall-cmd可以永久或非永久地改變配置,永久配置需要如man page中解釋的那樣改變(日了狗了)。
于是又去翻了翻firewalld(1)的man page,里面有兩段關于Runtime configuration跟Permanent configuration的解釋。
Runtime configuration
Runtime configuration is the actual active configuration and is not permanent. After
reload/restart of the service or a system reboot, runtime settings will be gone if they
haven’t been also in permanent configuration.Permanent configuration
The permanent configuration is stored in config files and will be loaded and become new
runtime configuration with every machine boot or service reload/restart.
運行時配置
運行時配置是實際上啟用了但不是永久的配置。在服務重載/重啟或系統重啟之后,運行時的設置如果不存在永久配置中,就會失效。
永久配置
永久配置被保存在配置文件中,隨著每次機器啟動或服務重載/重啟,永久配置都會被載入,變成新的運行時配置。
永久開啟端口
好了,說了那么多,應該是理清楚端口被自動關閉的原委了,那怎么永久開啟端口呢,萬能的Security Guide中給出了答案
The rules can be made permanent by adding the –permanent option using the firewall-cmd –permanent –direct command or by modifying /etc/firewalld/direct.xml.
只要添加規則時加上–permanent參數或者修改/etc/firewalld/direct.xml就行了。
所以只需要兩條命令
firewall-cmd --permanent --zone=public --add-port=2888/tcp
firewall-cmd --reload #重新載入服務
參考
- 4.5. USING FIREWALLS
- CentOS 7.0 - man page for firewalld (centos section 1) - Unix & Linux Commands
- centos 7 - open firewall port - Stack Overflow