Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Laravel] How to implement the schedule in Docker Laravel.

Posted on November 20, 2024December 20, 2024 By nim No Comments on [Laravel] How to implement the schedule in Docker Laravel.

Với Laravel bạn muốn khởi tạo 1 crontab hay schedule để sau 1 khoảng thời gian và đều dặn nó sẽ đi kiểm tra database hay làm việc gì đó thì bạn sẽ làm như thế nào

Vậy chúng ta cùng nghiên cứu schedule trong laravel.

Contents

Toggle
  • 1) Create a command via “php artisan”
  • 2) Run the laravel schedule in docker.
  • 3) Debug in Laravel command:

1) Create a command via “php artisan”

ở đây bạn sẽ cần code ra 1 command ví dụ như:
php artisan kang:return-stable-scale-object-k8s
=> Mục đích là command này sẽ query vào service và kiểm tra nếu cấu hình đó hết hạn thì nó thực hiện restore lại config mặc định.

Đầu tiền bạn run command để tạo class:

php artisan make:command ReturnStableScaleObjectK8s

Lúc này nó sẽ tạo ra file trong commands.

Lúc này bạn có thể thay đổi command theo ý thích.

Sau đó bạn code các logic trong funtion handle()

Tiếp đến bạn có thể chạy thử command:

Nếu command đã chạy thành công thì bạn cần setup nó vào schedule

Tiếp theo bạn vào console.php trong folder routes

<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();

Schedule::command('kang:return-stable-scale-object-k8s')->everyMinute();

Để run được schedule này bạn sẽ cần run command này để kiểm tra command đã được define trong schedule hay chưa?

php artisan schedule:run

Giờ ta phải dùng crontab để run command php artisan schedule:run

# my_laravel_docker_crontab
# m h  dom mon dow   command
# use the bin/bash as the default environment
* * * * * cd /var/www/html/ && php artisan schedule:run >> /tmp/cron-log.txt

# If your docker doesn't use the bin/bash as the default environment
* * * * * /bin/bash -l -c 'cd /var/www/html && php artisan schedule:run >> /tmp/cron-log.txt'

2) Run the laravel schedule in docker.

Mục tiêu chúng của chúng ta là phải run được schedule laravel trên Docker.

Chúng ta có Dockerfile:

# Refer to https://github.com/codityco/003-how-to-dockerise-a-laravel-project/blob/main/Dockerfile
### https://www.youtube.com/watch?v=uYhowDSkwyk
FROM php:8.3.12-apache

# Install dependencies
RUN apt-get update && \
    apt-get install -y \
    libzip-dev \
    zip \
    cron

# Enable mod_rewrite
RUN a2enmod rewrite

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql zip

ENV APACHE_DOCUMENT_ROOT=/var/www/html
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

# Copy the application code
COPY . /var/www/html
RUN chmod +x ./start.sh

# Set the working directory
WORKDIR /var/www/html

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

# Install project dependencies
RUN composer install

# Create Folder and File for SQLite
RUN mkdir -p /var/www/html/database/sqlite-data && \
    chown -R www-data:www-data /var/www/html/database/sqlite-data

# # Create a .env file from .env.example
# RUN if [ -f ".env.example" ]; then \
#         cp .env.example .env; \
#     else \
#         echo "No .env.example file found"; \
#     fi

# # Generate application key
# RUN php artisan key:generate --ansi

# Add docker custom crontab
ADD config/laravel_docker_crontab /etc/cron.d/my_laravel_docker_crontab
# Ensure newline at end of crontab file
# fix - new crontab file is missing newline before EOF, can't install.
RUN echo "" >> /etc/cron.d/my_laravel_docker_crontab
# Update the crontab file permission
RUN chmod 0644 /etc/cron.d/my_laravel_docker_crontab
# Specify crontab file for running
RUN crontab /etc/cron.d/my_laravel_docker_crontab


# Execute both Apache and cron
CMD ["./start.sh"]

các bạn sẽ thấy file start.sh

#!/bin/bash
service cron start

# Ensure the storage and cache directories have the correct permissions
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

# Define the files to check
FILES=(
    "/var/www/html/database/sqlite-data/database.sqlite"
    "/var/www/html/storage/logs/laravel.log"
)

# Define the user and group variables
USER="www-data"
GROUP="www-data"

# Loop through each file in the FILES array
for FILE in "${FILES[@]}"; do
    # Check if the file exists
    if [ ! -f "$FILE" ]; then
        echo "File does not exist at $FILE. Creating file..."
        touch "$FILE"
        # Change ownership of the directory where the file is located
        chown -R "$USER":"$GROUP" "$(dirname "$FILE")"
        echo "File created at $FILE and ownership set to $USER:$GROUP"
    else
        echo "File already exists at $FILE"
    fi
done

apache2-foreground

Tiếp đến là bạn define cấu hình crontab:

# my_laravel_docker_crontab
# m h  dom mon dow   command
# use the bin/bash as the default environment
* * * * * cd /var/www/html/ && php artisan schedule:run >> /tmp/cron-log.txt

# If your docker doesn't use the bin/bash as the default environment
* * * * * /bin/bash -l -c 'cd /var/www/html && php artisan schedule:run >> /tmp/cron-log.txt'

3) Debug in Laravel command:

Trong quá trình code thì check chắn bạn sẽ muốn kiểm tra lại kết quả và print nó ra màn hình console

$response = $this->rancherService->editScaleObject($envConfig['cluster_name'], $scaleObject['namespace'], $scaleObject['scale_object_id'], $scaleObjectConfig);
// // Debugging $response
// $this->info('Response: ' . json_encode($response)); // Logs the entire response as JSON
Laravel

Post navigation

Previous Post: [sweetalert2] Utilize SweetAlert2 to add an additional popup to your website.
Next Post: [laravel/Rancher] There are issues when retrieving Kubernetes data from Rancher by Laravel.

More Related Articles

[sweetalert2] Utilize SweetAlert2 to add an additional popup to your website. Laravel
[Laravel] This form is not secure. Autofill has been turned off Laravel
[Model/Laravel] hasMany Quan Hệ 1 Nhiều trong model Laravel
[Laravel] Create helper functions and call them as needed. Laravel
[Laravel] Create file controller in Laravel. Laravel
[php-laravel] Handle a new project laravel. Laravel

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025
  • [Windows] Remove the process that consumes too much CPU. June 3, 2025
  • Deploying Web-Based File Managers: File Browser and KubeFileBrowser with Docker and Kubernetes June 3, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.