1. zip安装nginx
1.1 安装必要组件
yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
1.2 安装nginx
wget http://nginx.org/download/nginx-1.19.9.tar.gz或yum install nginx
tar -zxvf nginx-1.19.9.tar.gz
cd nginx-1.19.9
1.3 将nginx安装在/usr目录下
./configure --prefix=/usr/local/nginx/
make PREFIX=/usr/local/nginx installs
make clean
1.4 启动nginx服务
cd /usr/local/nginx/sbin/
./nginx
1.5.指定配置文件重启nginx
/usr/local/nginx/sbin/nginx -s reload -c /usr/local/nginx/conf/nginx.conf
2. yum安装nginx
2.1 yum安装nginx
yum install -y nginx
2.2 启动停止指令
#启动nginx
systemctl start nginx.service
#停止nginx
systemctl stop nginx.service
#重启nginx
systemctl restart nginx.service
#开机启动nginx
systemctl enable nginx.service
3. docker安装nginx
3.1 拉取nginx官方镜像
docker pull nginx
3.2 创建nginx容器(适合无nginx.conf)
这种方式是第一次没用nginx配置文件所以先创建nginx容器然后将配置文件复制到主机
docker run -di --name nginx -p 80:80 nginx
脚本解析:
-di: 表示后台启动并开启控制台显示
-name 容器名为nginx
-p 容器端口和主机端口映射
最后的nginx 创建容器的镜像名
3.3 创建目录并将容器内的配置文件拷贝到指定目录
mkdir -p /usr/local/docker/nginx
docker cp nginx:/etc/nginx /usr/local/docker/nginx/conf
3.4 停止并删除nginx容器
docker stop nginx
docker rm nginx
3.5 创建nginx镜像并映射nginx.conf
docker run -di --name nginx -p 80:80 -v /usr/local/docker/nginx/conf:/etc/nginx nginx
3.6 docker nginx(可选)
docker run -p 8990:80 --name test-nginx -d --restart=always -e TZ="Asia/Shanghai" -v /home/test/file:/home/file test-nginx:latest
命令解析
-p:8990:80:主机8990端口映射容器内nginx80端口
-name:test-nginx:容器名为test-nginx
-d:容器后台运行
–restart=always:开机自启动
-e 设置环境变量:TZ="Asia/Shanghai":配置时区
-v 挂载目录 /home/test/file:/home/file:挂载主机/home/test/file 到容器/home/file
附录
nginx 静态资源配置
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://ip:port;
}
#1.root,请求 http://ip:port/upload/202308039904.gif 真实路径为:/home/file/upload/202308039904.gif
location /upload/{
root /home/file;
}
#2.alias只能存在location中,必须以/结束,请求 http://ip:port/upload/202308039904.gif 真实路径为:/home/file/202308039904.gif
#location /upload/{
# alias /home/file/;
#}
}
nginx websocket配置
# websocket代理
location /socket {
proxy_pass http://ip:port/;
#使用websocket
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
nginx反向代理
location /prod-api/{
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://ip:port/;
}