Recommend way to Artisan on Docker - php

I am yet to find an elegant and efficient way to run Laravel Artisan commands in my Docker based local dev environment.
Could anybody suggest the recommended or "proper" way to do things like migrations?
Or, has anybody found a neat way of doing this? Ideally with examples or suggestions.
Things that I've considered:
A new container (sharing the same volume and db link) with ssh, just for running commands (seems nasty).
Hacks in supervisor that could then end up running on live (not ideal).
Editing db configs, or trying to hack in a "host" environment, so that at least things like migrate can be run from the host.
Creating web front ends to run things (really nasty).
Trying to build a "signal" for it things.
I'm still getting my head around Docker and it's new-container-for-everything approach.
I suppose I want to balance cool-dev-ops stuff with why-do-I-need-another-fake-server-just-get-it-working-already.
I'd love to commit to it for my dev workflow, but it seems to become awkward to use under certain circumstances, like this one...
Any suggestions and ideas are welcome. Thanks all.

Docker 1.3 bring new command exec
So now you can "enter" running container like
docker exec -it my-container-name /bin/bash
After that you can run any command you want
php artisan --version

The best practice regarding Docker is to run each process inside it's own container. Therefore, the ideal way to run artisan commands is to have an image for creating containers specifically for this purpose.
I've created an image which can be pulled from the Docker Hub dylanlindgren/docker-laravel-artisan and it works really well. It's on GitHub as well if you want to take a look at the Dockerfile behind it.
I've also just written a blog post describing the way that all these seperate containers fit together.

There are a couple of possibilities...
Mounting a host directory in your container as the folder in which your Laravel app lives. That way you can just run php artisan migrate or composer update from the host. You might have problems with deployment, though, since you would have to replicate that part of your environment on the server.
adding an SSH server to your container (which is not recommended; here's a good discussion of that).
build and use nsenter, a tool for "entering" a running container and getting shell access. Note, I haven't used it, I just found it a while ago via a reference in the link above.
If you're primarily interested in deployment and you're doing it via a dockerfile, then the answer would be to add composer install and php artisan migrate to your dockerfile so they run when the container is built.
I'm interested in hearing more answers to this. It's something that I'm just getting into as well and would like to learn more about.

I use SSH and run migrations from a terminal inside the container.
I personally like Phusion's approach of using Docker as a 'lightweight virtual machine'. So I used their baseimage-docker which I've extended to create my own Docker image for Laravel applications.
I'm aware Phusion's image can be contentious in the Docker community, and that SSH is frowned upon by some who advocate Docker containers as microservices. But I'm happy with Phusion's approach until there are more established tools and practices for the multi-container approach.

I'm in the process of figuring out creating Docker images for Laravel projects, this is what I have so far.
FROM base_image_with_LAMP_stack_and_dependencies
WORKDIR /var/www/html/app
COPY composer.json composer.json
RUN composer install --no-scripts --no-dev --no-autoloader
COPY . .
RUN echo 'chown -R www-data:www-data /var/www/ \
&& composer dump-autoload \
&& cp .env.example .env \
&& php artisan key:generate \
&& php artisan migrate \
&& apachectl -D FOREGROUND' >> /root/container_init.sh && \
chmod 755 /root/container_init.sh
EXPOSE 80
CMD /root/container_init.sh
This way, there is no dependency on database during build time, and the migration process can run every time a new container is started.

Related

WebdriverIO and Docker Setup

I am trying to setup a docker container with WebdriverIO built into it, with the eventual aim of being able to run a CI/CD pipeline in gitlab, but I have absolutely no idea where to start.
My application is a PHP/MySQL based app which was also recently dockerised. I access it locally on http://localhost.
I have tried to create a docker image with wdio built into it, but it fails when trying to do the
npm init wdio --yes
as the --yes command doesn't force any of the default settings, which goes against the official documentation. This then causes the wdio installation to fail.
What is confusing me even more is that there seems to be very few tutorials for this, the wdio documentation doesn't seem great, and what tutorials I can find all seem to mention selenium. FYI, I am just a dev that has been tasked to take some existing WDIO scripts and get them ready for CI/CD, I don't know a massive amount about WDIO in the first place.
Does anyone have any basic steps I could follow that would describe the process of taking some local WDIO scripts, and getting them to run inside a container, with the end goal of being to have them into some sort of CI/CD pipeline?
When trying to create the image, the following command does not seem to work:
npm init wdio --yes
It would be much more appropriate if you have initialize a wdio project and copy it to the Dockerfile.
This is what it might look like:
FROM node:16
USER root
#===============================
# Set default workspace
#===============================
RUN mkdir /home/workspace \
&& chmod 2777 /home/workspace
COPY . /home/workspace
WORKDIR /home/workspace
This way, your docker image contains your whole project built in.
Then you could append the following command to make sure the environment is ready for webdriverI/O to execute.
#==================================
# Install needed packages
#==================================
RUN apt update && apt upgrade -y
RUN npm install
If you need anything like browser and webdriver, you could install it via dozens of approaches.
You can use ENTRYPOINT or CMD to make it execute the specified test suites once the container is up.
If you wanna complete CI or CD flow with docker containers, it will depend on which service you may utilize.

How to setup and run laravel, from git?

Either I miss something, or the whole chain lacks something.
Here's my assumption:
The whole point of containerization in development, is to reduce the cost of environment setup, and create a prepared image with all the required pieces.
So, when I read that Laravel Sail is installing laravel via containerization, I get excited. Thus I install it via their instructions, and everything works.
Then the problem begins. Because:
After a successful installation, I create a git repo, with GitHub's default laravel .gitignore
Then I push the newly installed laravel app into my git repo.
Then I ask a developer to start developing it. Please note that:
He does not have PHP installed
He does not have Composer installed
He clonse the repo, and as per installation guide, runs ./vendor/bin/sail up
But ./vender folder is correctly excluded in .gitignore
Thus his command results in:
bash: ./vendor/bin/sail: No such file or directory
He Googles it of course, and finds out that people suggest to run composer update
He goes to install composer, then before that PHP, then all extensoins of PHP, then ...
Do I miss something here? The whole point of containerization was to not install the required environment locally.
What is the proper way of running a laravel app, that is not installed from https://laravel.build, but is cloned from a git repo, WITHOUT having PHP or Composer installed locally?
Update
I found Bitnami laravel docker and it's exactly what containers should be.
You are right and the other developer doesn't need to have php nor composer installed.
All he/she needs is Docker installed on the local machine.
If you scaffolded the project with what is mentioned in the official Laravel docs under the Getting started section, then you will have a docker-compose.yml file in your project root directory.
For Windows
For Linux
For Mac OS
All the developer has to do after git cloning the repository is to run
docker-compose up --build -d
That's it.
For those struggling with this issue... I've found a command that work perfectly fine.
First of all, you don't need to locally have any PHP or Composer installed, maybe there is a misunderstanding about it, all you need is Docker.
Docker will install everything you need in something I understand is like a sandbox, not locally, for each project.
And for those downloaded projects, from GIT as example, that does not have vendor folder, and obviously cannot execute sail up you can simple execute:
docker run --rm --interactive --tty -v $(pwd):/app composer install
That command will download a composer image for docker, if you do not have one yet. Then, will run a composer install and you are free to execute a ./vendor/bin/sail up if you hadn't configured an alias or just sail up if you already configure an alias.
That's all.
The official documentation lists the following command.
docker run --rm \
-u "$(id -u):$(id -g)" \
-v $(pwd):/var/www/html \
-w /var/www/html \
laravelsail/php81-composer:latest \
composer install --ignore-platform-reqs
If you were to clone a Laravel project and run this command in the project root, it would create a very small container with php and composer installed and run composer in the project root to install all php dependencies. In effect, this installs the Laravel core code into the cloned project. Once the project in set up this way, the user should create a local .env file to match their development evironment.
cp .env.example .env # creates a .env file to be populated for the local environment
With the envronment set up, they can now create the application containers in docker and run the application. Laravel provides the Sail helper for this.
./vendor/bin/sail up -d # runs the docker containers in detached mode
Now it's a matter of setting up the laravel app and running the Laravel app. (I'm assuming the app uses one of the Laravel start kits that rely on Node.js. If you are using a Blade only application, you can skip the "npm" commands.)
sail artisan key:generate # (Best Practice) Generate a new application key on each machine
sail artisan migrate # Scaffold the database structure
sail artisan db:seed # (Optional) Seed the database with data
sail npm install # (Optional) Install front-end dependencies (Inertia, Vue, React, others...)
sail npm run dev # (Optional) Run the front-end framework in development mode
With this, the new developer should be running an exact copy of both the project and the development environment as the original developer.
Your project README may include additional steps to set up some other dependencies, but this is the basic workflow for contributing to a Laravel project.
The only prerequisites for this workflow is to have Docker installed with an Internet connection. This is most easily accomplished on Windows, Mac, and Linux by installing Docker Desktop.
Alternate for Older Projects
If you are working on an older project that doesn't use Laravel Sail, but does have a docker-compose.yml file, you should be able to build and run the necessary containers with the following command.
docker-compose up --build -d
Once you have the containers running, you would need to install the project dependencies directly into the container.
docker ps # find the container ID of your project's container
docker exec -it CONTAINER_ID php artisan key:generate
docker exec -it CONTAINER_ID php artisan migrate
docker exec -it CONTAINER_ID php artisan db:seed
docker exec -it CONTAINER_ID npm install
docker exec -it CONTAINER_ID npm run dev
Of course, Docker Desktop simplifies this process. With a button click you can have a terminal shell open directly in your container eliminating the need for the docker exec command.

Call phpunit from console in my symfony project

this is my current status:
I have a running symfony environment, based on a docker image. Everything works fine and from PHPStorm i can execute phpunit tests. But i want to execute them manually from console.
After i started all services by using docker-compose up --build, i login into the phpfpm service by: docker-compose exec -it phpfpm bash
then i move into my symfony project folder that contain all folders and files like "app/, bin/, vendor/, ... composer.json... etc"
I could go by calling vendor/phpunit/phpunit/phpunit but i want to get a shorter way. Is there any chance, maybe calling bin/phpunit or something like this?
Thanks in advance,
Max
PHPUnit has that script in the own composer.json, so bin (or vendor/bin) directory should contains a relevant symlink after running composer install. Also check your composer.json for bin-dir settings.
At least you always can create a symlink:
$ ln -s vendor/phpunit/phpunit/phpunit phpunit
According to the symfony docs the preferable way of using phpunit is by .phar file. In this way you can download phpunit as a .phar file and it will works both outside and inside docker container.
wget https://phar.phpunit.de/phpunit-6.0.phar
php phpunit-6.0.phar --version
Type now php phpunit-6.0.phar to run tests.

Make Capistrano use alias on sever when running scripts

I have the following problem using Capistrano with laravel:
My hosting provider does not provide a cli php version via php but only via a usr/bin/local/.../PHP-CLI command
I did create an alias for it in my .bash_profile so running composer install from the cli is no problem.
However, Capistrano (as far as I understand due to it starting in a very basic shell http://capistranorb.com/documentation/faq/why-does-something-work-in-my-ssh-session-but-not-in-capistrano/) does not load this alias, so I get an error from the composer scripts e.g. php artisan.
However, on my dev machine I need to keep it as php, since this is where php is here.
How can I solve this problem best? Any more info you need? Thanks.
Just in case it helps, this is how I call the script:
desc 'Composer install'
task :composer_install do
on roles(:app), in: :groups, limit:1 do
execute "/usr/local/bin/php5-56STABLE-CLI composer.phar install --working-dir #{fetch(:release_path)}"
execute "cp #{fetch(:deploy_to)}/shared/.env #{fetch(:release_path)}/.env"
end
end
It sounds like your scenario is the perfect fit for Capistrano's "command map" feature, as documented here: https://github.com/capistrano/sshkit#the-command-map.
Here are the two main takeaways:
Write your Capistrano execute commands so that the binary name (php) is a separate argument. This will allow it to be substituted using the command map. For example:
execute :php, "composer.phar install --working-dir #{fetch(:release_path)}"
In your Capistrano deployment config, tell the command map how to substitute the :php command, like this:
SSHKit.config.command_map[:php] = "/usr/local/bin/php5-56STABLE-CLI"
If you want this substitution to affect all deployment environments, place it in deploy.rb. If it only applies to your production environment, then put it in production.rb.
Okay, my current workaround is the following:
in your capistrano deploy.rb in the script that you execute at deploy update.
desc 'Composer install'
task :composer_install do
on roles(:app), in: :groups, limit:1 do
execute "/usr/local/bin/php5-56STABLE-CLI /path/to/composer.phar install --working-dir #{fetch(:release_path)} --no-scripts"
execute "cd #{fetch(:release_path)} && /usr/local/bin/php5-56STABLE-CLI artisan clear-compiled"
execute "cd #{fetch(:release_path)} && /usr/local/bin/php5-56STABLE-CLI artisan optimize"
end
end
end
after "deploy:updated", "deploy:composer_install"
I am not 100% sure if the artisan clear-compiled is needed. Anyway, those 2 are composer scripts that would normally be called via composer, but the --no-scripts flag keeps them from being called, so that it does not fail on install. When calling them from capistrano, I can easily change which php to use, as you can see.
However if anyone has a better solution, please let me know.

Replace PHP Class Dependencies from Git Bash

I'm using Laravel 5.2 and a RethinkDB service provider that uses a different dependency than normally migrated files, which is all handled for you if you write your migrations manually, but we build up our migrations using http://www.laravelsd.com/. During initial development tweaks occur so I wanted to write a quick bash script to run through /data/migrations/*.php files and replace the dependency if newly export migrations are dropped in. So far I've tried a bunch of different solutions with no luck and tried augmenting them too.
This seemed like it should work to replace Illuminate\Database\Schema\Blueprint with duxet\Rethinkdb\Schema\Blueprint:
cd database/migrations
grep --include={*.php} -rnl './' -e "Illuminate\Database\Schema\Blueprint" | xargs -i# sed -i 's/Illuminate\Database\Schema\Blueprint/duxet\Rethinkdb\Schema\Blueprint/g' #
Any suggestions why this isn't working? I don't see anything else in --help that would be useful.

Categories