2020-02-27 · 许进 · · 字数:665·阅读时间 2 分钟 阅读量

本文主要记录在阿里云ECS上安装配置Ngnix,通过公网域名访问多个Spring Boot应用。

1.安装Ngnix

1.yum安装Nginx

sudo yum install -y nginx

2.启动Nginx

systemctl start nginx.service

3.开机启动Nginx

systemctl enable nginx.service

2. Ngnix的常用命令

1.nginx -t 查看Ngnix的配置文件位置

[root@iZm5ei42hq2wbmbr6yb489Z ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

2.启动Ngnix

[root@iZm5ei42hq2wbmbr6yb489Z nginx]# nginx

3.停止Ngnix

[root@iZm5ei42hq2wbmbr6yb489Z nginx]# nginx -s stop

3. Ngnix配置总结

3.1 Nginx配置访问多个Spring Boot Jar

1.配置域名a.qingcloud.net访问端口为8080的应用

server {
    listen       80;
    server_name  a.qingcloud.net;
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
    }
}

2.配置域名b.qingcloud.net访问端口为8082的Spring Boot的应用

server {
    listen       80;
    server_name  b.qingcloud.net;
    location / {
        proxy_pass http://127.0.0.1:8082;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
    }
}

3.2 Ngnix配置访问静态资源

配置域名c.qingcloud.net访问某个文件夹下面的静态资源

server {
    listen 80; #暴露给外部访问的端口
    server_name c.qingcloud.net;
        charset utf-8;
    location / {
        #项目静态路径设置
        alias /usr/xujin/halo/;
    }
}

4.编写shell命令启动Spring Boot jar

4.1启动可执行Jar

sh halo-admin-mgmt.sh start

4.2 对应的shell脚本如下

#!/bin/bash

APP_NAME=/usr/xujin/jar/halo-admin-start-1.0.0.RELEASE.jar

#使用说明,用来提示输入参数
usage() {
    echo "Usage: sh halo-admin-mgmt.sh [start|stop|restart|status]"
    exit 1
}

#检查程序是否在运行
is_exist(){
  pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'`
  #如果不存在返回1,存在返回0     
  if [ -z "${pid}" ]; then
   return 1
  else
    return 0
  fi
}

#启动方法
start(){
  is_exist
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} is already running. pid=${pid}"
  else
    nohup java -jar ${APP_NAME}  >halo-admin.out 2>&1 &
  fi
}

#停止方法
stop(){
  is_exist
  if [ $? -eq "0" ]; then
    kill -9 $pid
  else
    echo "${APP_NAME} is not running"
  fi  
}

#输出运行状态
status(){
  is_exist
  if [ $? -eq "0" ]; then
    echo "${APP_NAME} is running. Pid is ${pid}"
  else
    echo "${APP_NAME} is NOT running."
  fi
}

#重启
restart(){
  stop
  sleep 5
  start
}

#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  "status")
    status
    ;;
  "restart")
    restart
    ;;
  *)
    usage
    ;;
esac