How to run cron and web application in same container? - php

I am new to docker. Hardly I have containerized my php application to run it in the web interface. But I have some cron to run with it. I learnt how to create separate cron image and run it from How to run a cron job inside a docker container?. But my use case is different. I need to use the php files from my php application container which seems not possible from my way. I tried creating the docker-compose.yml as follow to see if it would work
docker-compose.yml:
version: "3"
services:
app:
build:
context: ./docker/php
container_name: 'app'
restart: 'always'
ports:
- "80:80"
- "443:443"
links:
- db
volumes:
- ${DOCUMENT_ROOT-./src}:/var/www/html
- ${PHP_INI-./docker/php/php.ini}:/usr/local/etc/php/php.ini
- ${VHOSTS_DIR-./docker/apache2/vhosts}:/etc/apache2/sites-enabled
- ${LOG_DIR-./docker/logs/apache2}:/var/log/apache2
extra_hosts:
- "test.local:127.0.0.1"
hostname: cloudservice.local
domainname: local
#entrypoint: sh /var/www/html/cron.sh
As I have commented entry point here and if I do docker-compose up, everything works perfectly fine, My Dockerfile is as under
Dockerfile:
FROM php:7.2.27-apache
RUN apt-get update
RUN apt-get install -y cron
RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y
# Install useful tools
RUN apt-get -y install apt-utils nano wget dialog
# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl4 libcurl4-openssl-dev zip
# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Install xdebug
#RUN pecl install xdebug-2.5.0
#RUN docker-php-ext-enable xdebug
# Other PHP7 Extensions
RUN apt-get -y install libsqlite3-dev libsqlite3-0 default-mysql-client
RUN docker-php-ext-install pdo_mysql
RUN docker-php-ext-install pdo_sqlite
RUN docker-php-ext-install mysqli
RUN docker-php-ext-install curl
RUN docker-php-ext-install tokenizer
RUN docker-php-ext-install json
RUN apt-get -y install zlib1g-dev
RUN docker-php-ext-install zip
RUN apt-get -y install libicu-dev
RUN docker-php-ext-install -j$(nproc) intl
RUN docker-php-ext-install mbstring
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install -j$(nproc) gd
RUN pecl install redis-5.1.1 \
&& docker-php-ext-enable redis
# Enable apache modules
RUN a2enmod rewrite headers
My cron.sh file is as under
#!/usr/bin/env bash
# Ensure the log file exists
touch /var/www/html/logs/crontab.log
# Ensure permission on the command
chmod a+x /var/www/html/cron-local/hn-shc-rapid-daily.sh
# Added a cronjob in a new crontab
echo "* * * * * bash /var/www/html/cron-local/hn-shc-rapid-daily.sh >> /var/www/html/logs/crontab.log 2>&1" > /etc/crontab
# Registering the new crontab
crontab /etc/crontab
# Starting the cron
/usr/sbin/service cron start
# Displaying logs
# Useful when executing docker-compose logs mycron
tail -f /var/www/html/logs/crontab.log
But with the entry point commented, i cannot run cron. If i don't comment entrypoint, then cron runs, my web application doesn't. Is there any possibility to fix this?
Thanks

At the end of the docker file i added the following code after removing
RUN a2enmod rewrite headers
# Copy hello-cron file to the cron.d directory
COPY hello-cron /etc/cron.d/hello-cron #just any name
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron
# Apply cron job
RUN crontab /etc/cron.d/hello-cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
# Enable apache modules
RUN a2enmod rewrite headers
CMD cron && /usr/sbin/apache2ctl -D FOREGROUND
and cron.sh was changed to
* * * * * echo "hello world" >> /var/www/html/logs/crontab.log 2>&1
This worked for me. I need not have to add entry neither on docker-compose nor on docker file, but I guess entry also would work.
I don't know if this is the right way to do. If anyone would give me more advance idea, I would be happy to give it a try.
Thanks

I think it's better if you specify the entry point in the docker-compose file without "sh" in front of it. Remember that declaring a new entrypoint in the docker-compose file overwrites the entrypoint in the dockerfile. Link
I would advise you to create your own Entrypoint Script which will execute your crons in the container CMD ["/entrypoint.sh"]
Example:
Create an file and named "entrypoint.sh" or whatever and save it in the same folder where your Dockerfile is located. In this file push your Content from your cron.sh.
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install -j$(nproc) gd
RUN pecl install redis-5.1.1 \
&& docker-php-ext-enable redis
# Enable apache modules
RUN a2enmod rewrite headers
COPY entrypoint.sh /
RUN chmod +x /entrypoint.sh
CMD ["/entrypoint.sh"]
But you could also just add your cron directly in the docker file.
...
# Enable apache modules
RUN a2enmod rewrite headers
COPY your-cron.cron /
RUN crontab /your-cron.cron
...

Related

Docker container takes 8 seconds to execute simple php comand in windows

I was using a docker container with php:8.1.6-cli and running my laravel aplication.
When i attach the terminal to the container and run a simple command php artisan inspire the docker takes 8 seconds to execute.
My php.ini config:
file_uploads = On
allow_url_fopen = On
memory_limit = 256M
upload_max_filesize = 100M
max_execution_time = 360
date.timezone = America/Sao_Paulo
My Dockerfile for this container:
FROM php:8.1.6-cli
LABEL maintainer="Crazynds"
WORKDIR /workspace
ENV DEBIAN_FRONTEND noninteractive
ENV TZ=UTC-3
ENV NODE_VERSION=16
USER root
RUN apt-get update \
&& apt-get install -y libcurl4-openssl-dev libonig-dev libzip-dev libpq-dev build-essential gnupg gosu curl zip unzip git supervisor libcap2-bin libpng-dev python2 locales \
&& mkdir -p ~/.gnupg \
&& chmod 600 ~/.gnupg
RUN php -r "readfile('http://getcomposer.org/installer');" | php -- --install-dir=/usr/bin/ --filename=composer \
&& curl -sL https://deb.nodesource.com/setup_$NODE_VERSION.x | bash -
RUN apt-get install -y nodejs nano wget dos2unix
RUN apt-get -y autoremove \
&& apt-get clean\
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN pecl install redis && docker-php-ext-enable redis; exit 0
RUN docker-php-ext-install pdo_mysql pdo_pgsql mbstring exif pcntl curl zip gd
ENTRYPOINT ["sleep","infinity"]
How i find the problem that takes most of the time to execute the php comands?
Is there any way to check what is consuming each part of time in the execution?
I find the solution. The docker with volumes mounted using Windows dirs are slow.
The solution for my problem is to create the vendor folder and the node_modules in separated volumes, instead of mounting them from Windows folder.
That alone gave a big performance boost, now the response time is around 1 second, but if I mounted my entire project on the volume instead of a folder, it would be much faster.

Powershell module import not persisting in docker container image

I installed powershell in the php debian docker image and now I am installing PowerCLI module in the docker image to access the vsphere info and display using laravel. The issue is with the PowerCLI installation. Powershell doesn't seem to persist the modules installed and imported. When I import module and use RUN pwsh -c connect-viserver, it seems working in the docker-image. But when I call the cmdlet in laravel container as $process = new Process(['pwsh', '-c','Connect-VIServer', 'SERVERNAME']); it fails. I check to see if it is imported iin the powershell by accessing container docker exec -it app bash But the module is not installed. I am manually keeping the modules in a folder powershell/Modules and adding it to $env:$PSModulePath
I do not understand what I'm missing.
Here's is my docker file.
FROM php:7.4-fpm
# Copy composer.lock and composer.json
COPY composer.lock composer.json /var/www/
RUN pwd
# Set working directory
WORKDIR /var/www
RUN pwd
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpng-dev \
libjpeg62-turbo-dev \
libfreetype6-dev \
libonig-dev \
locales \
libzip-dev \
zip \
jpegoptim optipng pngquant gifsicle \
vim \
unzip \
git \
curl \
wget \
apt-utils
# 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 mysqli
RUN docker-php-ext-configure gd --enable-gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/
RUN docker-php-ext-install gd
RUN docker-php-ext-enable mysqli
# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
#########################
RUN pwd
# Download the Microsoft repository GPG keys
RUN wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb
# Register the Microsoft repository GPG keys
RUN dpkg -i packages-microsoft-prod.deb
# Update the list of products
RUN apt-get update
# Install PowerShell
RUN apt-get install -y powershell
# Start PowerShell
#RUN pwsh
# Allow installation from PSGallery
SHELL ["pwsh", "-command"]
RUN Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
#RUN Install-Module VMware.VimAutomation.Core -Confirm:$false
#RUN Import-Module VMware.VimAutomation.Core; Get-Module
#RUN Set-PowerCLIConfiguration -ParticipateInCEIP $false -Confirm:$false
#RUN Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
##RUN connect-viserver 10.21.24.9
RUN Get-Module -ListAvailable VMware.VimAutomation.Core | Import-Module
RUN $env:PSModulePath = $env:PSModulePath + ":/var/www/powershell/Modules"
RUN mkdir -p /root/.config/powershell
RUN touch /root/.config/powershell/Microsoft.PowerShell_profile.ps1
RUN echo "Get-Module -ListAvailable PowerCLI* | Import-Module" >> /root/.config/powershell/Microsoft.PowerShell_profile.ps1
RUN $PSHome
RUN Get-Module
SHELL ["/bin/sh", "-c"]
# 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
# Expose port 9000 and start php-fpm server
EXPOSE 9000
CMD ["php-fpm"]
RUN pwd
RUN ls -la && ls -la /var/www/powershell/Modules/

Setup a Docker container with only the docker-compose up command

I have an assessment in which I have to create a Docker container with CakePHP. I already have a working Docker container with CakePHP and I run the following commands for my container:
docker-compose build
docker-compose run cakephp composer install --no-interaction
docker-compose run cakephp bin/cake migrations migrate
docker-compose run cakephp bin/cake migrations seed
docker-compose up
The goal is to reduce the process down to only running the single command docker-compose up to be able to start testing the container. I'm very new to both Docker and CakePHP so I'm not sure how to do this.
Any help is greatly appreciated!
Dockerfile
#start with our base image (the foundation) - version 7.1.29
FROM php:7.1.29-apache
#install all the system dependencies and enable PHP modules
RUN apt-get update && apt-get install -y \
gcc \
make \
autoconf \
libc-dev \
pkg-config \
libicu-dev \
libpq-dev \
libmcrypt-dev \
mysql-client \
git \
zip \
unzip \
&& rm -r /var/lib/apt/lists/* \
&& docker-php-ext-configure pdo_mysql --with-pdo-mysql=mysqlnd \
&& docker-php-ext-install \
intl \
mbstring \
mcrypt \
pcntl \
pdo_mysql \
pdo_pgsql \
pgsql \
opcache
RUN set -eux; apt-get update; apt-get install -y libzip-dev zlib1g-dev; docker-php-ext-install zip
#install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin/ --filename=composer
ENV COMPOSER_ALLOW_SUPERUSER=1
#set our application folder as an environment variable
ENV APP_HOME /var/www/html
#change uid and gid of apache to docker user uid/gid
RUN usermod -u 1000 www-data && groupmod -g 1000 www-data
#change the web_root to laravel /var/www/html/public folder
RUN sed -i -e "s/html/html\/webroot/g" /etc/apache2/sites-enabled/000-default.conf
# enable apache module rewrite
RUN a2enmod rewrite && \
echo "ServerName localhost" >> /etc/apache2/apache2.conf
#copy source files and run composer
COPY . $APP_HOME
# install all PHP dependencies
RUN composer install --no-interaction
#change ownership of our applications
RUN chown -R www-data:www-data $APP_HOME
docker-compose.yml
version: '2'
services:
cakephp:
build: .
depends_on:
- mysql
links:
- "mysql"
ports:
- "4000:80"
volumes:
- .:/var/www/html/
environment:
- SECURITY_SALT= *some salt here*
- MYSQL_URL=mysql
- MYSQL_USERNAME=root
- MYSQL_PASSWORD=root
mysql:
image: mysql:5.6
volumes:
- mysql-data:/var/lib/mysql
environment:
- MYSQL_DATABASE=cakephp
- MYSQL_ROOT_PASSWORD=root
volumes:
mysql-data:
Option 1
What I usually do to reduce my commands when handling Docker and Docker Compose in general is using a Makefile.
So, in your case, you could write something like:
Makefile
SUDO := $(shell groups | grep -q docker || echo sudo)
.PHONY: start
start:
$(SUDO) docker-compose build \
&& $(SUDO) docker-compose run cakephp composer install --no-interaction \
&& $(SUDO) docker-compose run cakephp bin/cake migrations migrate \
&& $(SUDO) docker-compose run cakephp bin/cake migrations seed \
&& $(SUDO) docker-compose up
All you would have to do then is putting this file in your project folder and run make start.
(The $(SUDO) part ensures that you can run this comfortably even with a user that is not in the docker group.)
Option 2
To really just run docker-compose up (perhaps with --build flag), you would have to write a little script that you COPY into the Docker image (you're already doing that with COPY . $APP_HOME – provided that you put this script at where your Docker build context points to) and then use it as ENTRYPOINT.
Something like this should work for you.
entrypoint.sh:
#!/bin/sh
set -e
cakephp composer install --no-interaction
cakephp bin/cake migrations migrate
cakephp bin/cake migrations seed
exec "$#"
In your Dockerfile, you would then have to put ENTRYPOINT ["/bin/sh", "entrypoint.sh"]

custom make install in Docker file

Not able to run make install from docker file, not sure where I am going wrong.
Getting below error message when docker-compose build is run in ubuntu
Step 6/10 : RUN make install
---> Running in c8f67e8de3b5
make: *** No rule to make target 'install'. Stop.
ERROR: Service 'web' failed to build:
The command '/bin/sh -c make install' returned a non-zero code: 2
I have the below structure where server is laravel project and in root there is a docker-compose.yml file.
Below is the structure of server folder
docker-compose.yml file
version: '3'
services:
web:
image: api_server
container_name: api_server
build:
context: ./server/release
ports:
- 9000:80
volumes:
- ./server:/var/www/app
Dockerfile
FROM php:7.3.1-apache-stretch
RUN apt-get update -yqq && \
apt-get install -y apt-utils zip unzip && \
apt-get install -y nano && \
apt-get install -y libzip-dev libpq-dev libpng-dev&& \
a2enmod rewrite && \
docker-php-ext-install gd mbstring && \
docker-php-ext-install pdo_pgsql && \
docker-php-ext-install pgsql && \
docker-php-ext-configure zip --with-libzip && \
docker-php-ext-install zip && \
rm -rf /var/lib/apt/lists/*
RUN php -r "readfile('http://getcomposer.org/installer');" | php -- --install-dir=/usr/bin/ --filename=composer
COPY default.conf /etc/apache2/sites-enabled/000-default.conf
WORKDIR /var/www/app
RUN make install
RUN chown -R www-data:www-data /var/www/app/
RUN chmod -R 777 /var/www/app/storage
CMD ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
EXPOSE 80
server/Makefile
install:
# some other commands
composer install
refresh:
# For testing
php artisan migrate:refresh
php artisan db:seed
make run:
php artisan migrate:status
php artisan serve
Basically if I comment RUN make install and RUN chmod -R 777 /var/www/app/storage commands from Dockerfile it works. To test i'll get into the container and run the above 2 commands manually then it works by showing the default laravel page.
So I feel trying to run the above 2 commands from Dockerfile i guess source code isn't available at that point.

Cannot load PHP class when running Symfony command

I would appreciate any help I can get with following issue.
I've set up Symfony Messenger to use AMQP and RabbitMQ. I can dispatch message and make use of AMQPConnection within my project.
But when I try to consume the message I get following:
$ php bin/console messenger:consume-messages amqp
Attempted to load class "AMQPConnection" from the global namespace.
Did you forget a "use" statement for "PhpAmqpLib\Connection\AMQPConnection"?
The console command calls a method within AmqpFactory.php
public function createConnection(array $credentials): \AMQPConnection
{
return new \AMQPConnection($credentials);
}
So when I run the project from the browser, everything works fine. I can use AMQPConnection and all. But when running from terminal, it cannot find the AMQPConnection class.
From within my composer.json I also have the amqplib installed
"php-amqplib/php-amqplib": "^2.7",
I use Docker and the Dockerfile contains:
FROM php:7-apache
RUN usermod -u 1000 www-data &&\
a2dissite 000-default &&\
apt-get update &&\
apt-get install -y \
zlib1g-dev \
libicu-dev \
g++ \
libfreetype6-dev \
libssh-dev \
libjpeg62-turbo-dev \
libmcrypt-dev \
librabbitmq-dev \
libpng-dev &&\
docker-php-ext-configure intl &&\
docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ &&\
docker-php-ext-install -j$(nproc) gd pdo_mysql intl opcache zip pcntl exif bcmath sockets &&\
a2enmod rewrite
RUN pecl install amqp \
&& docker-php-ext-enable amqp
COPY docker/apache2.conf /etc/apache2/apache2.conf
WORKDIR /var/www/project
UPDATE!
I've printed the phpinfo() and when dispatching the message I have version 7.2.8 and when executing the terminal command I have 7.2.7. So terminal is not using the Docker instance of PHP when executing the command.
Solved this, finally. I had no idea I had to go via Docker to run this command. This worked for me:
docker exec -ti container_name sh -c "cd /var/www/project/ && php bin/console messenger:consume-messages amqp"
When using Docker, Symfony commands needs to be executed inside needed container.
The problem come from trying to execute php from the local host:
$ php bin/console messenger:consume-messages amqp
whereas the local host does not have the necessary dependencies, RabbitMQ in this case.
Instead the command should be run using the right container:
$ docker exec -ti container_name sh -c "cd /var/www/project/ && php bin/console messenger:consume-messages amqp"
container_name being the name of the container having the RabbitMQ dependencies.
You are missing package librabbitmq4 in your Docker container. Add RUN apt-get update --fix-missing && apt-get update && apt-get install php-amqp to your Dockerfile and rebuild the image.

Categories