1. 创建目录
mkdir -p /usr/local/nginx/conf
mkdir -p /usr/local/nginx/www
2. 创建配置文件
touch /usr/local/nginx/conf/nginx.conf
在nginx.conf文件添加如下配置,多个端口监听
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://www.baidu.com/;
}
location /api {
proxy_pass http://localhost:8080;
}
}
server {
listen 9000;
server_name localhost;
location / {
root /usr/share/nginx/html; # nginx工作目录是容器的而非宿主机
index index.html index.htm;
}
# axios 配置代理转发 解决浏览器禁止跨域
location /prod-api/ {
proxy_pass http://localhost:8080/;
}
}
}
3. 拉取镜像
docker pull nginx
查看镜像
docker images
4. 创建容器并启动
docker run -it -d
--name nginx
-p 80:80
-p 9000:9000
-v /usr/local/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
-v /usr/local/nginx/html:/usr/share/nginx/html
nginx
参数-v 表示挂载文件或目录,左边为宿主机位置,右边为容器位置,这样在宿主机修改的文件或目录会自动到容器内。如果不做配置文件的同步,宿主机修改的配置文件在容器无法生效;如果不做目录的挂载,通过nginx访问的资源会报404。
5. 查看容器
docker ps -a
6. 查看nginx启动日志
docker logs nginx
7. 启动、关闭、重启nginx
docker start nginx
docker stop nginx
docker restart nginx