1. Nginx介绍
2.Nginx安装
2.1 安装Nginx
docker-compose.yml
```yml
version: '3.1'
services:
nginx:
restart: always
image: daocloud.io/library/nginx:latest
container_name: nginx
ports:
- 80:80
volumes:
- /opt/docker_nginx/conf.d/:/etc/nginx/conf.d/
- /opt/docker_nginx/img/:/data/img
- /opt/docker_nginx/html/:/data/html
docker-compose up -d
![image.png](https://upload-images.jianshu.io/upload_images/26460997-1f00e41deffcd0ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查看容器id
进入容器内部
docker exec -it [CONTAINER ID]/[NAMES] bash
2.2 Nginx的配置文件
user nginx;
worker_processes 1;
# 以上统称为全局块
# worker_processes他的数值越大,Nginx的并发能力就越强
# error_log 代表Nginx的错误日志存放的位置
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# events块
# worker_connections他的数值越大,Nginx并发能力越强
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;
server{
listen 80;
server_name localhost;
location / {
root /data/html;
index index.html;
}
# 代理到html静态资源
#location /html {
# root /data;
# index index.html;
#}
# 代理到img静态资源
#location /img {
# root /data;
# autoindex on;
#}
# location块
# root: 将接收到的请求根据/data/html去查找静态资源
# index: 默认去上述的路径中找到index.html或者index.html
}
# server块
# listen: 代表Nginx监听的端口号
# localhost: 代表Nginx接收请求的ip
}
# http块
# include 代表引入一个外部的文件 -> /mime.types中存放着大量的媒体类型
# include /etc/nginx/conf.d/*.conf; -> 引入了conf.d目录下的以.conf为结尾的配置文件
测试访问:
3.Nginx服务器实现反向代理
4. Nginx实现负载均衡
4.1 轮询
upstream my-server{
server 10.131.87.243:8080;
server 10.131.87.243:8081;
}
server{
listen 80;
server_name localhost;
location / {
proxy_pass http://my-server/;
}
}
4.2 权重
4.3 ip_hash
5.Nginx实现动静分离
5.1 动态资源代理
location / {
proxy_pass 路径;
}
5.2 静态资源代理
location / {
root 静态资源路径;
index 默认访问路径下的什么资源;
autoindex on; # 代表展示静态资源全的全部内容,以列表的形式展开。
}
server{
listen 80;
server_name localhost;
代理到html静态资源
location /html {
root /data;
index index.html;
}
代理到img静态资源
location /img {
root /data;
autoindex on;
}
location块
root: 将接收到的请求根据/data/html去查找静态资源
index: 默认去上述的路径中找到index.html或者index.html
}