🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 创建 Nginx 虚拟主机 **Nginx** 是一个快速的、轻量级的 Web 服务器软件, 在许多情况下它已取代了 Apache,尤其是运行 Web 应用程序的情况。 然而,其配置语言与 Apache 相比并没有做什么重大改进,仍然不够简单清晰。 此外,大多数的配置文档只有俄语版,这也就解释了为什么你看到这么多份关于 "Understanding Russian for Nginx Administrators" 的拷贝。 #### 准备工作 你需要 [当文件更新时运行命令](#ch06sec06) 一节中曾使用的 Nginx 模块。 如果你像本章 [管理 Apache 服务](#ch07sec01) 一节中那样创建了 Apache 模块, 你还需要使用如下命令关闭 Apache 服务: ``` # service apache2 stop ``` #### 操作步骤 1. 添加如下代码到 /etc/puppet/modules/nginx/manifests/init.pp: ``` define site( $sitedomain = "" ) { include nginx if $sitedomain == "" { $vhost_domain = $name } else { $vhost_domain = $sitedomain } file { "/etc/nginx/sites-available/${vhost_domain}.conf": content => template("nginx/vhost.erb"), require => Package["nginx"], } file { "/etc/nginx/sites-enabled/${vhost_domain}.conf": ensure => link, target => "/etc/nginx/sites-available/${vhost_domain}. conf", require => File["/etc/nginx/sites-available/${vhost_ domain}.conf"], notify => Exec["reload nginx"], } } ``` 2. 使用如下内容创建 /etc/puppet/modules/nginx/templates/vhost.erb 文件: ``` server { listen 80; server_name <%= vhost_domain %>; access_log /var/log/nginx/<%= vhost_domain %>-access_log; root /var/www/<%= vhost_domain %>; } ``` 3. 创建目录 /var/www/bbqrecipes.com,使用适当的信息创建此目录下的 index.html 文件: ``` Welcome to the BBQ Recipes site! ``` 4. 添加如下代码到一个节点: ``` nginx::site { "bbqrecipes.com": } ``` 5. 运行 Puppet: ``` # puppet agent -test info: Retrieving plugin info: Caching catalog for cookbook. bitfieldconsulting.com info: Applying configuration version '1309198476' notice: /Stage[main]/Nginx/Package[nginx]/ensure: ensure changed 'purged' to 'present' notice: /Stage[main]//Node[cookbook]/Nginx::Site[bbqrecipes.com]/ File[/etc/nginx/sites-available/bbqrecipes.com.conf]/ensure: defined content as '{md5}fa92d2e7543b378e26827a063be34a31' notice: /Stage[main]//Node[cookbook]/Nginx::Site[bbqrecipes.com]/ File[/etc/nginx/sites-enabled/bbqrecipes.com.conf]/ensure: created info: /Stage[main]//Node[cookbook]/Nginx::Site[bbqrecipes.com]/ File[/etc/nginx/sites-enabled/bbqrecipes.com]: Scheduling refresh of Exec[reload nginx] notice: /Stage[main]/Nginx/Service[nginx]/ensure: ensure changed 'stopped' to 'running' notice: /Stage[main]/Nginx/Exec[reload nginx]: Triggered 'refresh' from 1 event notice: Finished catalog run in 21.45 seconds ``` #### 工作原理 以 bbqrecipes.com 为资源名对名为 nginx::site 的 define 创建一个实例, Puppet 会使用变量 vhost_domain 的值 bbqrecipes.com 调用 vhost.erb 模板生成相应的配置文件 bbqrecipes.com.conf。 此文件包含了 Nginx 为了响应对 domain 的请求所需要知道的一切, 并且指明了与 domain 对应的根文档目录所映射的文件系统位置。 #### 更多用法 与 Apache 不同,Nginx 直到现在还不支持动态模块。这就意味着, 如果想为其添加默认不包含的特殊功能,你必须自己重新编译 Nginx。 正确的做法是,使用你想要的选项编译 Nginx,然后创建一个软件包,将其放在自己的仓库中 (参见 [配置 APT 软件仓库](#ch05sec07) 一节的描述)提供给需要它的节点使用。 然而,一些使用 Puppet 的系统管理员希望省略这个步骤,直接提供源码包并在目标服务器上编译。 为了实现这点,可以使用 exec 资源通过类似于 [从源码包自动构建软件](#ch05sec09) 一节中描述的模式实现。 对于敏捷开发环境而言,被管理的有关产品几乎每隔几天就会有所变化,在这种情况下, 使用这种做法比不断重构软件包要迅速且节省由于重构软件包带来的成本。 #### 参见本书 * 本章的 [管理 Rails 应用程序](#ch07sec06) 一节