安装docker并运行:
[root@localhost ~]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
[root@localhost ~]# systemctl start docker
查看镜像库,没有nginx的可以用docker pull nginx
获取镜像。
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
[root@localhost ~]# docker pull nginx
Using default tag: latest
latest: Pulling from library/nginx
e5ae68f74026: Pull complete
21e0df283cd6: Pull complete
ed835de16acd: Pull complete
881ff011f1c9: Pull complete
77700c52c969: Pull complete
44be98c0fab6: Pull complete
Digest: sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest
[root@localhost ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest f652ca386ed1 2 weeks ago 141MB
使用nginx镜像来创建nginx容器
[root@localhost ~]# docker run --rm --name nginx-test -p 80:80 -d nginx
345d45dd2894ed81598bd15c62bf43c0c12f709ab13d904a31b2c0e39c99853c
- -d:在后台运行
- -p: 端口进行映射,将本地 8080 端口映射到容器内部的 80 端口
- –rm:容器停止运行后,自动删除容器文件
- –name nginx-test:容器的名字,自己定义
然后就可以通过80端口访问nginx了.
现在本地创建一个nginx文件夹,注意{}
中不能有空格。
[root@localhost ~]# mkdir -p /data/nginx/{html,logs}
[root@localhost ~]# dir /data/nginx/
html logs
查看启动的Nginx运行状态:
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
345d45dd2894 nginx "/docker-entrypoint.…" 7 minutes ago Up 7 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp nginx-test
把容器里面的 Nginx 配置文件拷贝到本地
[root@localhost ~]# docker cp 345d45dd2894:/etc/nginx /data/nginx/
[root@localhost ~]# dir /data/nginx/
html logs nginx
[root@localhost ~]# mv /data/nginx/nginx /data/nginx/conf
[root@localhost ~]# dir /data/nginx/conf/
conf.d fastcgi_params mime.types modules nginx.conf scgi_params uwsgi_params
配置反向代理,配置好后保存
[root@localhost ~]# vim /data/nginx/conf/conf.d/default.conf
server {
listen 80;
listen [::]:80;
# 这里的server_name一定要修改,不能为localhost。
server_name 10.102.10.240;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
# 设置反向代理
location /api/ {
proxy_pass http://192.168.0.100:8080/api/;
}
#error_page 404 /404.html;
......
配置生效后,所有/api/开头的地址都会被重定向到设置的地址。
例如访问http://10.102.10.240/api/test.txt
,会返回http://192.168.0.100:8080/api/test.txt
的内容。
停止之前创建的容器,重新新建一个容器并映射目录。
[root@localhost ~]# docker stop nginx-test
nginx-test
[root@localhost ~]# docker run -d -p 80:80 --name nginx-web -v /data/nginx/html:/usr/share/nginx/html -v /data/nginx/conf:/etc/nginx -v /data/nginx/logs:/var/log/nginx nginx
7fd5ee130f570748d6f21f01586efacd46ce40a3cbf4a952e095f32de4332ca3
如果修改了配置文件,需要重新启动一下服务:
docker exec -it nginx-web nginx -s reload