Docker容器配置Laravel任务调度器遇权限问题求助
Hey there, let's get to the bottom of that cron can't open or create /var/run/crond.pid permission denied error. The core issue is that you're running your container as the non-root www user, but cron defaults to writing its PID file to /var/run/—a directory owned by root, which your www user doesn't have access to. Here are two reliable solutions to resolve this:
Solution 1: Use a Custom PID File Path (Recommended, Keeps Non-Root Execution)
This approach lets you keep running as the www user by telling cron to use a PID file in a directory that www has permissions for.
Step 1: Update Your Dockerfile
Add a step to create a dedicated run directory for cron's PID file, and grant ownership to the www user. Insert this before the USER www line:
# Create a writable directory for cron's PID file RUN mkdir -p /var/www/run && chown www:www /var/www/run
Step 2: Fix Your entrypoint.sh
There were also a couple of syntax errors in your original entrypoint script. Replace it with this corrected version:
#!/bin/bash echo "Docker container has been started" # Write the Laravel schedule cron job to a file echo "* * * * * php /var/www/artisan schedule:run >> /var/log/cron.log 2>&1" > scheduler.txt crontab scheduler.txt # Ensure the cron log file exists and is writable touch /var/log/cron.log && chmod 666 /var/log/cron.log # Start cron with a custom PID file in the writable directory cron -f -P /var/www/run/crond.pid
- The
-Pflag tells cron to use the specified PID file path instead of/var/run/crond.pid. - We also make sure the cron log file exists and has proper permissions so
wwwcan write to it.
Solution 2: Run Cron as Root, Then Switch to www for PHP-FPM
If you prefer to keep cron running with root privileges (still safe if you configure the cron job to run as www), you can adjust your setup to start cron as root first, then switch to the www user for PHP-FPM.
Step 1: Update Your Dockerfile
Remove the USER www line—we'll handle user switching in the entrypoint script instead:
# Remove the existing USER www line ADD entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT /entrypoint.sh EXPOSE 9000
Step 2: Update entrypoint.sh
#!/bin/bash echo "Docker container has been started" # Configure cron as root, but run the artisan command as www echo "* * * * * su - www -c 'php /var/www/artisan schedule:run' >> /var/log/cron.log 2>&1" > scheduler.txt crontab scheduler.txt # Start cron in the background cron -f & # Switch to www user and start php-fpm (exec keeps it as the foreground process) exec su - www -c "php-fpm"
- The
su - www -cpart ensures the Laravel schedule runs with the correct user permissions, even though cron is running as root. - Using
execfor php-fpm makes it the container's foreground process, which keeps the container running properly.
Either of these solutions should fix the permission error and get your Laravel task scheduler working in Docker.
内容的提问来源于stack exchange,提问作者Sushant Kargwal

