Nginx

Laravel docker cron nginx 502 網關錯誤問題

  • July 9, 2020

我在 docker 容器中使用我的 laravel 應用程序。一切正常,直到我向 dockerfile 添加了一個 cron。我需要安排一份工作,所以我需要一個 cron。我的撰寫文件看起來像這樣

version: '3'

networks:
 laravel:
   driver: bridge

services:
 nginx:
   image: nginx:stable
   container_name: nginx
   ports:
     - "8080:80"
   volumes:
     - ./src:/var/www/html
     - ./nginx/default.conf:/etc/nginx/conf.d/default.conf
   depends_on:
     - php
     - mysql
   networks:
     - laravel

 php:
   build:
     context: .
     dockerfile: Dockerfile
   container_name: php
   volumes:
     - ./src:/var/www/html
   ports:
     - "9000:9000"
   networks:
     - laravel

nginx 配置文件看起來像這樣

server {
   listen 80;
   index index.php index.html;
   server_name localhost;
   error_log  /var/log/nginx/error.log;
   access_log /var/log/nginx/access.log;
   root /var/www/html/public;

   location / {
       try_files $uri $uri/ /index.php?$query_string;
   }

   location ~ \.php$ {
       try_files $uri =404;
       fastcgi_split_path_info ^(.+\.php)(/.+)$;
       fastcgi_pass php:9000;
       fastcgi_index index.php;
       include fastcgi_params;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param PATH_INFO $fastcgi_path_info;
   }
}

我的 docker 文件看起來像這樣

FROM php:7.3-fpm

WORKDIR /var/www/html

# RUN docker-php-ext-install pdo pdo_mysql mysqli
# RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
RUN docker-php-ext-install mysqli pdo pdo_mysql && docker-php-ext-enable mysqli

# Install cron
RUN apt-get update && apt-get install -y cron

# Add crontab file in the cron directory
ADD src/app/schedule/crontab /etc/cron.d/cron

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD printenv > /etc/environment && echo "cron starting..." && (cron) && : > /var/log/cron.log && tail -f /var/log/cron.log

並且 nginx 日誌中的錯誤是

2020/07/06 08:27:06 [error] 5#5: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.19.0.2:9000", host: "localhost:8080"

nginx 正在執行

/nginx - 172.19.0.7

這裡出了什麼問題?

最後我找到了解決方案

我們需要替換 docker 文件的最後一行。

請使用這個

CMD cron && docker-php-entrypoint php-fpm

代替

CMD printenv > /etc/environment && echo "cron starting..." && (cron) && : > /var/log/cron.log && tail -f /var/log/cron.log

引用自:https://serverfault.com/questions/1024300