nignx简单入门
简介: nignx服务器
什么是Nginx
Nginx 是⼀款⾼性能的 http 服务器/反向代理服务器及电⼦邮件(IMAP/POP3)代理服务器。由俄罗斯 的程序设计师伊⼽尔·⻄索夫(Igor Sysoev)所开发,官⽅测试 nginx 能够⽀⽀撑 5 万并发链接,并且 cpu、内存等资源消耗却⾮常低,运⾏⾮常稳定。
Nginx应⽤场景:
1、http 服务器。Nginx 是⼀个 http 服务可以独⽴提供 http 服务。可以做⽹⻚静态服务器。
2、虚拟主机。可以实现在⼀台服务器虚拟出多个⽹站。例如个⼈⽹站使⽤的虚拟主机。
3、反向代理,负载均衡。当⽹站的访问量达到⼀定程度后,单台服务器不能满⾜⽤户的请求时,需要⽤ 多台服务器集群可以使⽤ nginx 做反向代理。并且多台服务器可以平均分担负载,不会因为某台服务器 负载⾼宕机⽽某台服务器闲置的情况。
1.安装nginx
这⾥使⽤docker安装nginx,linux如何安装nginx参考⽂档Nginx在Linux下的安装.md
- 搜索nginx镜像
docker search nginx
- 拉取nginx镜像
docker pull nginx
- 创建容器,设置端⼝映射、⽬录映射
# 在/root⽬录下创建nginx⽬录⽤于存储nginx数据信息
mkdir ~/nginx
cd ~/nginx
mkdir conf
cd conf
# 在~/nginx/conf/下创建nginx.conf⽂件,粘贴下⾯内容 vim nginx.conf
user nginx;
worker_processes 1;error_log /var/log/nginx/
error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include / etc / nginx / mime.types;
default_type application/octet - stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
access_log / var / log / nginx / access.log main;
sendfile on;#tcp_nopush on;
keepalive_timeout 65;#gzip on;
include / etc / nginx / conf.d/*.conf;}
~/nginx/conf.d/80.conf
server {
listen 80; # 监听的端⼝
server_name localhost; # 域名或ip
location / { # 访问路径配置
root /usr/share/nginx/html;# 根⽬录
index index.html index.htm; # 默认⾸⻚
}
error_page 500 502 503 504 /50x.html; # 错误⻚⾯
location = /50x.html {
root html;
}
}
server {
listen 80; # 监听的端⼝
server_name localhost; # 域名或ip
location / { # 访问路径配置
root /usr/share/nginx/html;# 根⽬录
index index.html index.htm; # 默认⾸⻚
}
error_page 500 502 503 504 /50x.html; # 错误⻚⾯
location = /50x.html {
root html;
}
}
参数说明:
-p 80:80:将容器的 80端⼝映射到宿主机的 80端⼝。
-v $PWD/conf/nginx.conf:/etc/nginx/nginx.conf:将主机当前⽬录下的
/conf/
nginx.conf 挂载到容器的 :/etc/nginx/nginx.conf。配置⽬录
-
v $PWD/logs:/var/log/nginx:将主机当前⽬
录下的 logs ⽬录挂载到容器
的/var/log/nginx。⽇志⽬录
4.使⽤外部机器访问nginx
2.Nginx静态⽹站部署
1、静态⽹站的部署
将静态⻚⾯/index⽬录下的所有内容 上传到服务器的/usr/local/nginx/html下即可访问
2、 配置虚拟主机
虚拟主机,也叫“⽹站空间”,就是把⼀台运⾏在互联⽹上的物理服务器划分成多个“虚拟”服务器。虚拟主 机技术极⼤的促进了⽹络技术的应⽤和普及。同时虚拟主机的租⽤服务也成了⽹络时代的⼀种新型经济 形式。
端⼝绑定
修改配置文件
3.域名绑定
修改上面配置文件
4.配置反向代理
1.1、什么是反向代理
反向代理(Reverse Proxy)⽅式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内 部⽹络上的服务器,并 将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器 对外就表现为⼀个反向代理服务器。
修改上面配置文件
5.负载均衡
修改上面配置文件
客户端,此时代理服务器 对外就表现为⼀个反向代理服务器。
修改上面配置文件
[外链图片转存中…(img-8yAT3mPC-1643085791182)]
5.负载均衡
修改上面配置文件
[外链图片转存中…(img-6AmmKdv3-1643085791183)]