Nginx 反向代理实现

Nginx 反向代理实现

反向代理原理

安装nginx

 第一步:进入nginx.org官网

 

 

 2 创建缓存

第一步:下载工具
yum install yum-utils -y

第二步:创建文件配置文件并编辑文件
touch /etc/yum.repos.d/nginx.repo

编辑文件
vim /etc/yum.repos.d/nginx.repo

输入内容为
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
第三步:创建缓存
yum makecache
第四步:安装nginx
yum install nginx -y

第五步:配置nginx反向代理

  

cd到该文件夹下

  cd /etc/nginx/conf.d/

  编辑default.conf文件

  vim default.conf

  先清空文件,然后再粘贴配置文件内容

  

upstream django {
server 127.0.0.1:38000; #配置要代理的端口号以及ip地址
}

server {
listen 80;
server_name _;
location / {
proxy_pass http://django;
index index.html index.htm;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

  保存退出。

第六步:检测配置文件是否正确

 

 nginx -t

  如果内容没错,还是报错,则可能是空格或特殊字符问题,只需要删除空格,再重新空格即可  

第七步: 启动nginx

  

nginx -g 'daemon off;'    #nginx在前台启动

  注意:如果没反应,可能是防火墙没关,关掉即可

  systemctl status firewalld   #查看防火墙状态

  systemctl stop firewalld    #关闭防火墙

第八步:创建一个teach文件夹,在teach文件夹内再创建一个django,nginx文件夹

 

 cd到 nginx 开始构建nginx镜像

  在nginx中创建一个Dockerfile

Dockerfile文件内容

FROM centos:7

#安装yum工具
RUN yum install yum-utils -y

#创建nginx源的文件
ADD nginx.repo /etc/yum/repos.d/    #将nginx.repo中的内容添加至/etc/yum/repos.d/

#刷新yum缓存
RUN yum makecache

#安装Nginx
RUN yum install nginx -y

#复制配置文件
ADD default.conf /etc/nginx/conf.d/

#设置启动命令 
CMD nginx -g 'daemon off;'

注意在创建nginx源的时候跑配置好源

在nginx文件夹下

vim nginx.repo

 

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true


在nignx中的default.conf中配置反向代理相关内容

upstream django {
server BBS:8002;   #通过容器名,代理的端口及ip
}

server {
listen 83;     #Nginx监听的端口
server_name _;
location / {
proxy_pass http://django;
index index.html index.htm;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}


原文地址:https://www.cnblogs.com/ltyc/p/14093581.html