shell脚本多实例部署nginx的详细教程

  

下面是关于“shell脚本多实例部署nginx的详细教程”的完整攻略。

准备工作

在开始之前,我们需要先进行一些准备工作。

1. 安装必要的软件

我们需要安装以下软件:

  • nginx
  • supervisor

在 Ubuntu 系统上,可以通过以下命令来安装:

sudo apt-get install nginx supervisor

2. 创建目录及配置文件

etc/nginx/ 目录下创建 sites-availablesites-enabled 两个子目录,并创建一个 nginx.conf 配置文件。

创建 sites-available 目录:

mkdir /etc/nginx/sites-available

创建 sites-enabled 目录:

mkdir /etc/nginx/sites-enabled

创建 nginx.conf 配置文件:

touch /etc/nginx/nginx.conf

然后在 nginx.conf 中加入以下语句:

include /etc/nginx/sites-enabled/*.conf;

3. 配置 supervisor

etc/supervisor/conf.d/ 目录下创建一个 nginx.conf 配置文件。

创建 nginx.conf 配置文件:

touch /etc/supervisor/conf.d/nginx.conf

nginx.conf 中加入以下语句:

[program:nginx]
command=/usr/sbin/nginx
autostart=true
autorestart=true
startretries=3
stderr_logfile=/var/log/nginx/nginx.err.log
stdout_logfile=/var/log/nginx/nginx.out.log
user=root

步骤

接下来,我们开始进行具体的步骤。

1. 编写 shell 脚本

下面是一个示例的 shell 脚本,该脚本根据传入的参数来创建不同的 nginx 实例。

创建 nginx-instance.sh 文件并加入以下代码:

#!/bin/bash

# 定义变量
INSTANCE_NAME=${1:-"nginx"}
INSTANCE_PORT=${2:-"80"}
INSTANCE_ROOT=${3:-"/var/www/html"}
CONFIG_FILE="/etc/nginx/sites-available/${INSTANCE_NAME}.conf"
PID_FILE="/run/nginx-${INSTANCE_NAME}.pid"

# 判断是否已存在该实例
if [[ -f "$CONFIG_FILE" ]]; then
  echo "Error: instance already exists"
  exit 1
fi

# 创建配置文件
cat << EOF > "$CONFIG_FILE"
server {
    listen ${INSTANCE_PORT} default_server;
    listen [::]:${INSTANCE_PORT} default_server;

    root ${INSTANCE_ROOT};
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}
EOF

# 创建软链接
ln -s "$CONFIG_FILE" "/etc/nginx/sites-enabled/${INSTANCE_NAME}.conf"

# 重启 nginx
supervisorctl restart nginx

# 提示信息
echo "Success: instance has been created!"
echo "Instance name: ${INSTANCE_NAME}"
echo "Instance port: ${INSTANCE_PORT}"
echo "Instance root: ${INSTANCE_ROOT}"

2. 导入配置文件

nginx.conf 中加入以下语句:

include /etc/nginx/sites-enabled/*.conf;

3. 启动 supervisor

启动 supervisor:

sudo systemctl start supervisor

4. 创建 nginx 实例

使用以下命令创建 nginx 实例:

sudo sh nginx-instance.sh instance1 8080 /var/www/html/instance1

这将会创建一个名为 instance1 的 nginx 实例,监听 8080 端口,并把 /var/www/html/instance1 设置为根目录。

5. 测试 nginx 实例

使用以下命令测试 nginx 实例:

curl -I http://localhost:8080/

如果返回类似以下的信息,即表示 nginx 实例已经成功创建并启动了:

HTTP/1.1 200 OK
Server: nginx/1.14.0 (Ubuntu)
Date: Wed, 29 Sep 2021 07:04:16 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 612
Connection: keep-alive
Last-Modified: Mon, 06 Aug 2018 07:05:36 GMT
ETag: "264-57366c26672ce"
Accept-Ranges: bytes

示例1

下面是示例1:

假设我们希望创建一个名为 mysite 的 nginx 实例,并将其监听在 8000 端口,并将默认的根目录设置为 /var/www/mysite,我们可以使用以下命令:

sudo sh nginx-instance.sh mysite 8000 /var/www/mysite

示例2

下面是示例2:

假设我们希望创建一个名为 photosite 的 nginx 实例,并将其监听在 8080 端口,并将默认的根目录设置为 /var/www/photosite,我们可以使用以下命令:

sudo sh nginx-instance.sh photosite 8080 /var/www/photosite

总结

通过以上步骤,我们成功的实现了 shell 脚本多实例部署 nginx 的功能,并且还提供了两个示例供大家参考。希望对大家有所帮助。

相关文章