发布于  更新于 

Docker 安装 Nginx 并挂载目录

1.拉取镜像

1
docker pull nginx

2.创建容器

1
docker docker run -d --name nginx -p 80:80 nginx

Bash 执行 docker ps 查看

dockerps

3.创建挂载目录

为什么要创建挂载目录?因为docker容器内部有自己的文件系统,在主机创建挂载目录并关联 Nginx 容器的配置目录后,以后可以通过修改主机下的配置目录文件来直接影响到容器内的配置。

1
mkdir -p /data/nginx/{conf,log,html}

把 Nginx 容器中的文件复制到主机

1
2
3
docker cp nginx:/etc/nginx/nginx.conf /data/nginx/conf/nginx.conf
docker cp nginx:/etc/nginx/conf.d /data/nginx/conf/conf.d
docker cp nginx:/usr/share/nginx/html /data/nginx/

4.停止并删除 Nginx 容器

执行 docker stop + 容器ID的前两位

1
2
docker stop 6a
docker rm 6a

5.重新创建容器

1
2
3
4
5
6
docker run -d --name nginx -p 80:80 \
-v /data/nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /data/nginx/conf/conf.d:/etc/nginx/conf.d \
-v /data/nginx/log:/var/log/nginx \
-v /data/nginx/html:/usr/share/nginx/html \
--privileged=true nginx

执行docker ps 查看运行状态,如果启动失败执行 docker logs + 容器ID前两位 查看报错。

6.验证

1
curl localhost

出现以下内容说明安装成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

或者打开浏览器输入服务器 IP 验证

image-20240620171653544

至此安装完成。