Search code examples
laraveldockercrontaskscheduling

Setting laravel task scheduler in the docker container


Can anyone help in setting the laravel scheduler in the docker container? I have installed and set up the server using docker. But to setup a cron job(laravel task scheduler) in the docker container, I am getting the issue.

Here is my Dockerfile

FROM php:7.2-fpm

# Copy composer.lock and composer.json
COPY composer.lock composer.json /var/www/

# Set working directory
WORKDIR /var/www/

# Install dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    default-mysql-client \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    locales \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl\
    cron

# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install extensions
RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
RUN docker-php-ext-configure gd --with-gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-png-dir=/usr/include/
RUN docker-php-ext-install gd

# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Add user for laravel application
RUN groupadd -g 1000 www
RUN useradd -u 1000 -ms /bin/bash -g www www


# Copy existing application directory contents
COPY . /var/www/

# Copy existing application directory permissions
COPY --chown=www:www . /var/www/


# Change current user to www
USER www

ADD entrypoint.sh /entrypoint.sh

RUN chmod +x /entrypoint.sh

ENTRYPOINT /entrypoint.sh

# Expose port 9000 and start php-fpm server
EXPOSE 9000
CMD ["php-fpm"]

And My Entrypoint.sh file code this

#!/bin/bash

# Start the run once job. echo "Docker container has been started"

# Setup a cron schedule
* * * * * php /var/www/artisan schedule:run >> /var/log/cron.log 2>&1
# This extra line makes it a valid cron" > scheduler.txt

crontab scheduler.txt 
cron -f

I am always getting this error when making a container up.

cron can't open or create /var/run/crond.pid permission denied


Solution

  • Create a bin folder and in that add file run-scheduler.sh file in which the laravel schedular command is stated which eventually hits this command.

    #!/usr/bin/env bash

    while [ true ]

    do

    php /var/www/artisan schedule:run --verbose --no-interaction &

    sleep 60

    done

    After this declare a entrypoint.sh file in which the start docker command is stated which hits eventually every 60 sec by run-scheduer.sh. #!/bin/bash

    ./bin/run-scheduler.sh &

    docker-php-entrypoint php-fpm