我正在设置一个用于研究目的的小型Web项目,包含两个docker容器(一个nginx
容器和一个php
容器)。
我已经链接了我的容器,我现在可以直接从nginx容器请求静态文件(.js,.css ...),并通过套接字请求/index.php
到php
容器。
但到目前为止,我无法处理/
上的请求。
我依靠this example来构建我的nginx配置。 下面的代码示例和解释引起了我的注意:
location / {
index index.html index.php;
}
[...]
location ~ \.php$ {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name;
include fastcgi_params;
}
[请求“/”]仅与前缀位置“/”匹配,因此, 它由这个位置处理。然后索引指令测试 存在[index.php]。 [如果它]存在,则指令执行 内部重定向到“/index.php”,nginx搜索位置 再次好像请求是由客户发送的。
由于我使用的是docker容器,nginx进程和php worker在两个不同的文件系统中工作。因此index.php
文件位于php
容器中,而不在nginx
中。因此,nginx无法找到此文件并返回404错误。
这是否意味着我应该 - 即使它听起来很脏 - 在两个容器中复制php源两次?或者有更好的方法来解决这个问题吗?返回301到/index.php
是否正确?
答案 0 :(得分:1)
您需要使用docker 持久存储,即又称卷。
将项目文件移动到它,当容器启动时,您需要将项目文件映射到每个docker容器。 (Docker将通过符号链接来实现)
然后,你的nginx容器将路由到php容器使用项目文件的同一个地方,一切都会正常工作。
您可以在此答案中找到有关docker persistent storage的详细信息: How to deal with persistent storage (e.g. databases) in docker
另外,我的建议是使用 docker-compose 工具。使用它可以非常轻松地管理多个容器和卷。它使用YAML格式配置,例如卷设置将如下所示:
volumes:
# Just specify a path and let the Engine create a volume
- /var/lib/mysql
# Specify an absolute path mapping
- /opt/data:/var/lib/mysql
# Path on the host, relative to the Compose file
- ./cache:/tmp/cache
# User-relative path
- ~/configs:/etc/configs/:ro
# Named volume
- datavolume:/var/lib/mysql
我的建议是使用phpdocker.io生成准备好的YAML,这将有助于您了解如何构建良好的docker生态系统并快速移动。