Docker Community Forums

Share and learn in the Docker community.

Laravel docker cron nginx 502 bad gateway issue (111: Connection refused) while connecting to upstream)

I am using laravel app in a docker container. Everything worked fine until I added a cron to the dockerfile. I need to schedule a job so I need a cron.
My compose file looks like this

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

the nginx config file looks like this

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;
    }
}

My docker file looks like this

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

and the error in the nginx log is

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"

the nginx is running at

/nginx - 172.19.0.7

What is going wrong here?

At last I found the solution

we need to replace the last line of the docker file.

Please use this

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

instead of

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