Nginx Docker 卷为空

Nginx Docker Volumes empty

使用 docker-compose 时,nginx 不会像其他图像那样显示文件。

以Mysql为例,下面的代码会将在/var/lib/mysql创建的数据保存到本地机器./volumes/db/data

./volumes/db/data:/var/lib/mysql

另一个例子,使用 Wordpress,下面的代码会将在 /var/www/html/wp-content/uploads 创建的数据保存到本地计算机 ./volumes/uploads/data

./volumes/uploads/data:/var/www/html/wp-content/uploads

这不适用于 nginx,所以无论我将 /some/nginx/path 更改为什么,它都不会出现在 ./volumes/nginx/data

./volumes/nginx/data:/some/nginx/path

nginx 在这方面的工作方式是否不同?


更新

使用具有以下配置的命名卷解决了这个问题:


volumes:
  nginx_data:
    driver: local
    driver_opts:
      o: bind
      device: ${PWD}/volumes/nginx/data

应该没有什么区别,volume就是将本地目录挂载到容器中的目录。要么你没有正确安装,要么你在 nginx 容器中安装了错误的路径(nginx 不使用的路径)。

基于 https://docs.docker.com/samples/library/nginx/ 上的官方 nginx docker 图像文档,您应该挂载到 /usr/share/nginx/html

$ docker run --name some-nginx -v /some/content:/usr/share/nginx/html:ro -d nginx

此外,我会在您的 docker-compose.yaml:

中包含完整路径
volumes:
  - /full_path/volumes/nginx/data:/usr/share/nginx/html

如果这仍然不起作用,您应该执行到容器中并确认目录已挂载:

$ docker exec -it <container_name> sh
$ df -h | grep nginx

# write data, confirm you see it on the docker host's directory
$ cd /usr/share/nginx/html
$ touch foo

# on docker host
$ ls /full_path/volumes/nginx/data/foo

如果其中任何一个失败,我会查看 docker 日志以查看挂载目录是否存在问题,可能是路径或权限问题。

$ docker logs <container_name>

---更新---

我 运行 你正在使用的一切,它都有效:

$ cat Dockerfile
FROM nginx
RUN touch /usr/share/nginx/html/test1234 && ls /usr/share/nginx/html/


$ docker build -t nginx-image-test .; docker run -p 8889:80 --name some-nginx -v /full_path/test:/usr/share/nginx/html:rw -d nginx-image-test; ls ./test;
...

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                  NAMES
33ccbea6c1c1        nginx-image-test    "nginx -g 'daemon of…"   4 minutes ago       Up 4 minutes        0.0.0.0:8889->80/tcp   some-nginx

$ cat test/index.html
hello world

$ curl -i http://localhost:8889
HTTP/1.1 200 OK
Server: nginx/1.15.3
Date: Thu, 06 Sep 2018 15:35:43 GMT
Content-Type: text/html
Content-Length: 12
Last-Modified: Thu, 06 Sep 2018 15:31:11 GMT
Connection: keep-alive
ETag: "5b91483f-c"
Accept-Ranges: bytes

hello world

-- 更新 2 -- 太棒了,你想通了,这个 post 似乎解释了原因:

The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile because built images should be portable. A host directory wouldn’t be available on all potential hosts.

If you have some persistent data that you want to share between containers, or want to use from non-persistent containers, it’s best to create a named Data Volume Container, and then to mount the data from it.

我 运行 在尝试创建一个卷以将我自己的 nginx 配置放入 etc/nginx 时也遇到过这个问题。虽然我从未发现真正的问题,但我认为这与如何从 Dockerfile 构建 nginx 有关。

我通过使用自己的 Dockerfile 扩展原始文件并在构建时复制配置文件解决了这个问题。希望这对您有所帮助。

FROM nginx:1.15.2

COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./global /etc/nginx/global
COPY ./conf.d /etc/nginx/conf.d