php - 我应该在两个容器中复制 index.php 吗?

标签 php nginx docker

我正在建立一个用于研究目的的小型 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;
}

[A request “/”] is matched by the prefix location “/” only, therefore, it is handled by this location. Then the index directive tests for the existence of [index.php]. [If it] exists, then the directive does an internal redirect to “/index.php”, and nginx searches the locations again as if the request had been sent by a client.



由于我使用的是 docker 容器,因此 nginx 进程和 php 工作人员在两个不同的文件系统中工作。所以index.php文件位于 php容器而不是 nginx .因此 nginx 不会找到这个文件并返回 404 错误。

这是否意味着我应该 - 即使听起来很脏 - 在两个容器中复制 php 源代码两次? 或者有没有更好的方法来解决这个问题?将 301 返回到 /index.php是正确的方式吗?

最佳答案

您需要使用 docker 持久存储 ,又名卷。

将您的项目文件移动到其中,当容器启动时,您需要将项目文件映射到每个 docker 容器。 (Docker 将通过符号链接(symbolic link)来完成)

然后,您的 nginx 容器将路由到 php 容器使用项目文件的同一位置,并且一切正常。

您可以在此答案中找到有关 docker 持久存储的详细信息:
How to deal with persistent storage (e.g. databases) in docker

另外,我的建议是使用 docker 撰写 工具。使用它管理多个容器和卷非常容易。它使用 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 生态系统并快速行动。

关于php - 我应该在两个容器中复制 index.php 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45335967/

相关文章:

php - 不在对象上下文中时使用 $this

php - 从父类调用扩展类函数

php - Yii 框架 : Display associated table entry through foreign key and search against it

php - 如何从选择框中选择多个选项

python - bottle 如何返回二进制文件

nginx - 无法以非root用户身份运行nginx容器

apache - 如何限制对我无法仅通过其他引用应用程序控制的应用程序的访问?

docker - 如何使用docker-compose连接到数据库,该docker-compose连接到本地计算机上的另一服务(redash&mysql&python_script)

spring-boot - 如何使用Gradle Kotlin DSL对Spring Boot应用程序进行Docker化

amazon-web-services - Amazon Linux AMI 上的 Docker