<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Pascal Landau - Software Engineering]]></title><description><![CDATA[Technical Director Marketing Intelligence & Marketing Technology - into Software Engineering, PHP, Docker and Google BigQuery]]></description><link>https://pascallandau.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 01:05:34 GMT</lastBuildDate><atom:link href="https://pascallandau.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Use git-secret to encrypt secrets in the repository [Tutorial Part 6]]]></title><description><![CDATA[How to use git-secret to encrypt secrets and store them in a git repository This article appeared first on at Use git-secret to encrypt secrets in the…]]></description><link>https://pascallandau.hashnode.dev/use-git-secret-to-encrypt-secrets-in-the-repository-tutorial-part-6</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/use-git-secret-to-encrypt-secrets-in-the-repository-tutorial-part-6</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Git]]></category><category><![CDATA[Docker]]></category><category><![CDATA[encryption]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Mon, 04 Jul 2022 04:50:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1656910630692/GjOqlvFdc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How to use git-secret to encrypt secrets and store them in a git repository</p>
<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/git-secret-encrypt-repository-docker/">Use git-secret to encrypt secrets in the repository [Tutorial Part 6]</a></p><p></p>
<hr />

<p>In the sixth part of this tutorial series on developing PHP on Docker we will <strong>setup <code>git-secret</code> to store secrets directly in the repository</strong>. Everything will be handled through Docker and  added as make targets for a convenient workflow.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/git-secret-encrypt-repository-docker/git-secret-example.gif">![git-secret example](https://www.pascallandau.com/img/git-secret-encrypt-repository-docker/git-secret-example.gif "git-secret example")</a></p>
<p>
FYI:  This tutorial is a precursor to the next a part 
<a href="https://www.pascallandau.com/blog/ci-pipeline-docker-php-gitlab-github/">Create a CI pipeline for dockerized PHP Apps</a>
because dealing with secrets is an important aspect when setting up a CI system (and later when  deploying to production) - but I feel it's complex enough to warrant its own article.
</p>
<div class="youtube">
<iframe width="560" height="315" src="https://www.youtube.com/embed/pZ-vFMfKcLY"></iframe>
</div>

<p><strong>All code samples are publicly available</strong> in my <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.   You find the branch with the final result of this tutorial at <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-6-git-secret-encrypt-repository-docker">part-6-git-secret-encrypt-repository-docker</a>.</p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/php-qa-tools-make-docker/">Set up PHP QA tools and control them via make</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/ci-pipeline-docker-php-gitlab-github/">Create a CI pipeline for dockerized PHP Apps</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>

<p><a id="table-of-contents"> </a>
</p>
<h2 id="heading-table-of-contents">Table of contents</h2>

<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#tooling">Tooling</a><ul>
<li><a class="post-section-overview" href="#gpg">gpg</a><ul>
<li><a class="post-section-overview" href="#gpg-installation">gpg installation</a></li>
<li><a class="post-section-overview" href="#gpg-usage">gpg usage</a><ul>
<li><a class="post-section-overview" href="#create-gpg-key-pair">Create GPG key pair</a></li>
<li><a class="post-section-overview" href="#export-list-and-import-private-gpg-keys">Export, list and import private GPG keys</a></li>
<li><a class="post-section-overview" href="#export-list-and-import-public-gpg-keys">Export, list and import public GPG keys</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#git-secret">git-secret</a><ul>
<li><a class="post-section-overview" href="#git-secret-installation">git-secret installation</a><ul>
<li><a class="post-section-overview" href="#the-git-permission-issue">The <code>git</code> permission issue</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#git-secret-usage">git-secret usage</a><ul>
<li><a class="post-section-overview" href="#initialize-git-secret">Initialize git-secret</a><ul>
<li><a class="post-section-overview" href="#the-git-secret-directory-and-the-gpg-agent-socket">The <code>git-secret</code> directory and the <code>gpg-agent</code> socket</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#adding-listing-and-removing-users">Adding, listing and removing users</a><ul>
<li><a class="post-section-overview" href="#reminder-rotate-the-encrypted-secrets">Reminder: Rotate the encrypted secrets</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#adding-listing-and-removing-files-for-encryption">Adding, listing and removing files for encryption</a></li>
<li><a class="post-section-overview" href="#encrypt-files">Encrypt files</a></li>
<li><a class="post-section-overview" href="#decrypting-files">Decrypting files</a></li>
<li><a class="post-section-overview" href="#show-changes-between-encrypted-and-decrypted-files">Show changes between encrypted and decrypted files</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#makefile-adjustments">Makefile adjustments</a></li>
<li><a class="post-section-overview" href="#workflow">Workflow</a><ul>
<li><a class="post-section-overview" href="#process-challenges">Process challenges</a><ul>
<li><a class="post-section-overview" href="#updating-secrets">Updating secrets</a></li>
<li><a class="post-section-overview" href="#code-reviews-and-merge-conflicts">Code reviews and merge conflicts</a></li>
<li><a class="post-section-overview" href="#local-git-secret-and-gpg-setup">Local <code>git-secret</code> and <code>gpg</code> setup</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#scenarios">Scenarios</a><ul>
<li><a class="post-section-overview" href="#initial-setup-of-gpg-keys">Initial setup of <code>gpg</code> keys</a></li>
<li><a class="post-section-overview" href="#initial-setup-of-git-secret">Initial setup of <code>git-secret</code></a></li>
<li><a class="post-section-overview" href="#initialize-gpg-after-container-startup">Initialize <code>gpg</code> after container startup</a></li>
<li><a class="post-section-overview" href="#adding-new-team-members">Adding (new) team members</a></li>
<li><a class="post-section-overview" href="#adding-and-encrypting-files">Adding and encrypting files</a></li>
<li><a class="post-section-overview" href="#decrypt-files">Decrypt files</a></li>
<li><a class="post-section-overview" href="#removing-files">Removing files</a></li>
<li><a class="post-section-overview" href="#removing-team-members">Removing team members</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#pros-and-cons">Pros and cons</a><ul>
<li><a class="post-section-overview" href="#pro">Pro</a></li>
<li><a class="post-section-overview" href="#cons">Cons</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#wrapping-up">Wrapping up</a></li>
</ul>


<p><a id="introduction"> </a>
</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Dealing with secrets (passwords, tokens, key files, etc.) is close to "naming things" when it comes to hard problems in software engineering. Some things to consider:</p>
<ul>
<li><strong>security is paramount</strong> - but high security often goes hand in hand with high inconvenience<ul>
<li>and if things get too complicated, people look for shortcuts...</li>
</ul>
</li>
<li>in a team, <strong>sharing certain secret values</strong> is often mandatory<ul>
<li>so now we need to think about secure ways to distribute and update secrets across multiple
people</li>
</ul>
</li>
<li>concrete secret values often <strong>depend on the environment</strong><ul>
<li>inherently tricky to "test" or even "review", because those values are "by definition"
different on "your machine" than on "production"</li>
</ul>
</li>
</ul>
<p>In fact, entire products have been build around dealing with secrets, e.g. <a target="_blank" href="https://www.vaultproject.io/">HashiCorp Vault</a>, <a target="_blank" href="https://aws.amazon.com/secrets-manager/">AWS Secrets Manager</a> or the <a target="_blank" href="https://cloud.google.com/secret-manager">GCP Secret Manager</a>. Introducing those in a project comes with a certain overhead as it's yet another service that needs to be integrated and   maintained. Maybe it is the exactly right decision for your use-case - maybe it's overkill. By the end of this article you'll at least be aware of an alternative with a lower barrier to entry. See also the <a class="post-section-overview" href="#pros-and-cons">Pros and cons</a> section in the end for an overview.</p>
<p>Even though it's <a target="_blank" href="https://withblue.ink/2021/05/07/storing-secrets-and-passwords-in-git-is-bad.html">generally not advised to store secrets in a repository</a>, I'll propose exactly that in this tutorial:</p>
<ul>
<li>identify files that contain secret values</li>
<li>make sure they are added to <code>.gitignore</code></li>
<li>encrypt them via <code>git-secret</code></li>
<li>commit the encrypted files to the repository</li>
</ul>
<p>In the end, we will be able to call</p>
<pre><code class="lang-bash">make secret-decrypt
</code></pre>
<p>to reveal secrets in the codebase, make modifications to them if necessary and then run</p>
<pre><code class="lang-bash">make secret-encrypt
</code></pre>
<p>to encrypt them again so that they can be committed (and pushed to the remote repository). To  see it in action, check out branch <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/git-secret-encrypt-repository-docker">part-6-git-secret-encrypt-repository-docker</a> and run the following commands:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># checkout the branch</span>
git checkout part-6-git-secret-encrypt-repository-docker

<span class="hljs-comment"># build and start the docker setup</span>
make make-init
make docker-build
make docker-up

<span class="hljs-comment"># "create" the secret key - the file "secret.gpg.example" would usually NOT live in the repo!</span>
cp secret.gpg.example secret.gpg

<span class="hljs-comment"># initialize gpg</span>
make gpg-init

<span class="hljs-comment"># ensure that the decrypted secret file does not exist</span>
ls passwords.txt

<span class="hljs-comment"># decrypt the secret file</span>
make secret-decrypt

<span class="hljs-comment"># show the content of the secret file</span>
cat passwords.txt
</code></pre>

<p><a id="tooling"> </a>
</p>
<h2 id="heading-tooling">Tooling</h2>
<p>We will set up <code>gpg</code> and <code>git-secret</code> in the php <code>base</code> image, so that the tools become available in all other containers. Please refer to <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022</a> for an in-depth explanation of the docker images.</p>
<div class="panel panel-default">
  <div class="panel-heading">
    <strong>Caution</strong>
  </div>
  <div class="panel-body bg-danger">
    All following commands are 
    <strong>executed <em>in</em> the <code>application</code> container.</strong>
    <br />
    <br />
    <strong>Tip:</strong>
    <br />
    See <a href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#easy-container-access-via -din-bashrc-helper">Easy container access via din .bashrc helper</a>
    for a convenient shortcut to log into docker containers.
  </div>
</div>


<p>Please note, that there is a caveat when using <code>git-secret</code> in a folder that is shared between  the host system and a docker container. I'll explain that in more detail (including a workaround)  in section  <a class="post-section-overview" href="#the-git-secret-directory-and-the-gpg-agent-socket">The <code>git-secret</code> directory and the <code>gpg-agent</code> socket</a>.</p>

<p><a id="gpg"> </a>
</p>
<h3 id="heading-gpg">gpg</h3>
<p><code>gpg</code> is short for <a target="_blank" href="https://gnupg.org/">The GNU Privacy Guard</a> and is an open source implementation of the OpenPGP standard. In short, it allows us to create a personal key file pair (similar to SSH keys) with a private secret key and a public key that can be shared with other parties whose messages you want to decrypt.</p>

<p><a id="gpg-installation"> </a>
</p>
<h4 id="heading-gpg-installation">gpg installation</h4>
<p>To install it, we can simply run <code>apk add gnupg</code> and thus update  <code>.docker/images/php/base/Dockerfile</code> accordingly</p>
<pre><code class="lang-Dockerfile"># File: .docker/images/php/base/Dockerfile

RUN apk add --update --no-cache \
        bash \
        gnupg \
        make \
#...
</code></pre>

<p><a id="gpg-usage"> </a>
</p>
<h4 id="heading-gpg-usage">gpg usage</h4>
<p>I'll only cover the strictly necessary <code>gpg</code> commands here. Please refer to <a target="_blank" href="https://git-secret.io/#using-gpg">the "Using GPG" section in the <code>git-secret</code> docu</a> and/or <a target="_blank" href="https://linuxhint.com/generate-gpg-keys-gpg/">How to generate PGP keys with GPG</a> for further information.</p>

<p><a id="create-gpg-key-pair"> </a>
</p>
<h5 id="heading-create-gpg-key-pair">Create GPG key pair</h5>
<p>We need <code>gpg</code> to <strong>create the gpg key pair</strong> via</p>
<pre><code class="lang-bash">name=<span class="hljs-string">"Pascal Landau"</span>
email=<span class="hljs-string">"pascal.landau@example.com"</span>
gpg --batch --gen-key &lt;&lt;EOF
Key-Type: 1
Key-Length: 2048
Subkey-Type: 1
Subkey-Length: 2048
Name-Real: <span class="hljs-variable">$name</span>
Name-Email: <span class="hljs-variable">$email</span>
Expire-Date: 0
%no-protection
EOF
</code></pre>
<p>The <code>%no-protection</code> will create a key without password, see also <a target="_blank" href="https://gist.github.com/woods/8970150">this gist to "Creating gpg keys non-interactively"</a>. To use a password (e.g. <code>12345678</code>, we could have replace the <code>%no-protection</code> line with</p>
<pre><code class="lang-text">Passphrase: 12345678
</code></pre>
<p>All options for the unattended creation are defined in the  <a target="_blank" href="https://www.gnupg.org/documentation/manuals/gnupg/Unattended-GPG-key-generation.html">official docs at "Unattended key generation"</a>.</p>
<p>Output:</p>
<pre><code class="lang-text">$ name="Pascal Landau"
$ email="pascal.landau@example.com"
$ gpg --batch --gen-key &lt;&lt;EOF
&gt; Key-Type: 1
&gt; Key-Length: 2048
&gt; Subkey-Type: 1
&gt; Subkey-Length: 2048
&gt; Name-Real: $name
&gt; Name-Email: $email
&gt; Expire-Date: 0
&gt; %no-protection
&gt; EOF
gpg: key E1E734E00B611C26 marked as ultimately trusted
gpg: revocation certificate stored as '/root/.gnupg/opengpg-revocs.d/74082D81525723F5BF5B2099E1E734E00B611C26.rev'
</code></pre>
<p>You could also run <code>gpg --gen-key</code> without the <code>--batch</code> flag to be guided interactively through the process.</p>

<p><a id="export-list-and-import-private-gpg-keys"> </a>
</p>
<h5 id="heading-export-list-and-import-private-gpg-keys">Export, list and import private GPG keys</h5>
<p>The <strong>private key can be exported</strong> via</p>
<pre><code class="lang-bash">email=<span class="hljs-string">"pascal.landau@example.com"</span>
path=<span class="hljs-string">"secret.gpg"</span>
gpg --output <span class="hljs-string">"<span class="hljs-variable">$path</span>"</span> --armor --export-secret-key <span class="hljs-string">"<span class="hljs-variable">$email</span>"</span>
</code></pre>
<p><strong>This secret key must never be shared</strong>!</p>
<p>It looks like this:</p>
<pre><code class="lang-text">-----BEGIN PGP PRIVATE KEY BLOCK-----

lQOYBF7VVBwBCADo9un+SySu/InHSkPDpFVKuZXg/s4BbZmqFtYjvUUSoRAeSejv
G21nwttQGut+F+GdpDJL6W4pmLS31Kxpt6LCAxhID+PRYiJQ4k3inJfeUx7Ws339
XDPO3Rys+CmnZchcEgnbOfQlEqo51DMj6mRF2Ra/6svh7lqhrixGx1BaKn6VlHkC
...
ncIcHxNZt7eK644nWDn7j52HsRi+wcWsZ9mjkUgZLtyMPJNB5qlKQ18QgVdEAhuZ
xT3SieoBPd+tZikhu3BqyIifmLnxOJOjOIhbQrgFiblvzU1iOUOTOcSIB+7A
=YmRm
-----END PGP PRIVATE KEY BLOCK-----
</code></pre>
<p>All <strong>secret keys can be listed</strong> via</p>
<pre><code class="lang-bash">gpg --list-secret-keys
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">$ gpg --list-secret-keys
/root/.gnupg/pubring.kbx
------------------------
sec   rsa2048 2022-03-27 [SCEA]
      74082D81525723F5BF5B2099E1E734E00B611C26
uid           [ultimate] Pascal Landau &lt;pascal.landau@example.com&gt;
ssb   rsa2048 2022-03-27 [SEA]
</code></pre>
<p>You can <strong>import the private key</strong> via</p>
<pre><code class="lang-bash">path=<span class="hljs-string">"secret.gpg"</span>
gpg --import <span class="hljs-string">"<span class="hljs-variable">$path</span>"</span>
</code></pre>
<p>and get the following output:</p>
<pre><code class="lang-text">$ path="secret.gpg"
$ gpg --import "$path"
gpg: key E1E734E00B611C26: "Pascal Landau &lt;pascal.landau@example.com&gt;" not changed
gpg: key E1E734E00B611C26: secret key imported
gpg: Total number processed: 1
gpg:              unchanged: 1
gpg:       secret keys read: 1
gpg:  secret keys unchanged: 1
</code></pre>
<p><strong>Caution:</strong> If the secret key requires a password, you would now be prompted for it. We can  circumvent the prompt by using <code>--batch --yes --pinentry-mode loopback</code>:</p>
<pre><code class="lang-bash">path=<span class="hljs-string">"secret.gpg"</span>
gpg --import --batch --yes --pinentry-mode loopback <span class="hljs-string">"<span class="hljs-variable">$path</span>"</span>
</code></pre>
<p>See also <a target="_blank" href="https://betakuang.medium.com/using-command-line-passphrase-input-for-gpg-with-git-for-windows-f78ae2c7cd2e">Using Command-Line Passphrase Input for GPG</a>. In doing so, we don't need to provide the password just yet - but we must pass it later when we  attempt to <a class="post-section-overview" href="#decrypting-files">decrypt files</a>.</p>

<p><a id="export-list-and-import-public-gpg-keys"> </a>
</p>
<h5 id="heading-export-list-and-import-public-gpg-keys">Export, list and import public GPG keys</h5>
<p>The <strong>public key can be exported</strong> to <code>public.gpg</code> via</p>
<pre><code class="lang-bash">email=<span class="hljs-string">"pascal.landau@example.com"</span>
path=<span class="hljs-string">"public.gpg"</span>
gpg --armor --<span class="hljs-built_in">export</span> <span class="hljs-string">"<span class="hljs-variable">$email</span>"</span> &gt; <span class="hljs-string">"<span class="hljs-variable">$path</span>"</span>
</code></pre>
<p>It looks like this:</p>
<pre><code class="lang-text">-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBF7VVBwBCADo9un+SySu/InHSkPDpFVKuZXg/s4BbZmqFtYjvUUSoRAeSejv
G21nwttQGut+F+GdpDJL6W4pmLS31Kxpt6LCAxhID+PRYiJQ4k3inJfeUx7Ws339
...
3LLbK7Qxz0cV12K7B+n2ei466QAYXo03a7WlsPWn0JTFCsHoCOphjaVsncIcHxNZ
t7eK644nWDn7j52HsRi+wcWsZ9mjkUgZLtyMPJNB5qlKQ18QgVdEAhuZxT3SieoB
Pd+tZikhu3BqyIifmLnxOJOjOIhbQrgFiblvzU1iOUOTOcSIB+7A
=g0hF
-----END PGP PUBLIC KEY BLOCK-----
</code></pre>
<p><strong>List all public keys</strong> via</p>
<pre><code class="lang-bash">gpg --list-keys
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">$ gpg --list-keys
/root/.gnupg/pubring.kbx
------------------------
pub   rsa2048 2022-03-27 [SCEA]
      74082D81525723F5BF5B2099E1E734E00B611C26
uid           [ultimate] Pascal Landau &lt;pascal.landau@example.com&gt;
sub   rsa2048 2022-03-27 [SEA]
</code></pre>
<p>The <strong>public key can be imported</strong> in the same way as private keys via</p>
<pre><code class="lang-bash">path=<span class="hljs-string">"public.gpg"</span>
gpg --import <span class="hljs-string">"<span class="hljs-variable">$path</span>"</span>
</code></pre>
<p>Example:</p>
<pre><code class="lang-text">$ gpg --import /var/www/app/public.gpg
gpg: key E1E734E00B611C26: "Pascal Landau &lt;pascal.landau@example.com&gt;" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1
</code></pre>

<p><a id="git-secret"> </a>
</p>
<h3 id="heading-git-secret">git-secret</h3>
<p>The official website of <a target="_blank" href="https://git-secret.io/">git-secret</a> is already doing a great job of introducing the tool. In short, it allows us to <strong>declare certain files as "secrets"</strong> and <strong>encrypt them via <code>gpg</code></strong> - using the keys of all trusted parties. The encrypted file can then by <strong>stored safely directly in the git repository</strong> and <strong>decrypted if required</strong>.</p>
<p>In this tutorial I'm using <code>git-secret v0.4.0</code></p>
<pre><code class="lang-text">$ git secret --version
0.4.0
</code></pre>

<p><a id="git-secret-installation"> </a>
</p>
<h4 id="heading-git-secret-installation">git-secret installation</h4>
<p>The <a target="_blank" href="https://git-secret.io/installation#alpine">installation instructions for Alpine</a> read as follows:</p>
<pre><code class="lang-bash">sh -c <span class="hljs-string">"echo 'https://gitsecret.jfrog.io/artifactory/git-secret-apk/all/main'"</span> &gt;&gt; /etc/apk/repositories
wget -O /etc/apk/keys/git-secret-apk.rsa.pub <span class="hljs-string">'https://gitsecret.jfrog.io/artifactory/api/security/keypair/public/repositories/git-secret-apk'</span>
apk add --update --no-cache git-secret
</code></pre>
<p>Plus, we need to account for a recent change in <code>git</code> that requires that the parent directory is  owned by the user executing the <code>git</code> command. See also the more detailed explanation in section <a class="post-section-overview" href="#the-git-permission-issue">The <code>git</code> permission issue</a>.</p>
<p>We update the <code>.docker/images/php/base/Dockerfile</code> accordingly:</p>
<pre><code class="lang-Dockerfile"># File: .docker/images/php/base/Dockerfile

# install git-secret
# @see https://git-secret.io/installation#alpine
ADD https://gitsecret.jfrog.io/artifactory/api/security/keypair/public/repositories/git-secret-apk /etc/apk/keys/git-secret-apk.rsa.pub

RUN echo "https://gitsecret.jfrog.io/artifactory/git-secret-apk/all/main" &gt;&gt; /etc/apk/repositories  &amp;&amp; \
    apk add --update --no-cache \
        bash \
        git-secret \
        gawk \
        gnupg \
        make \
#...

# Fix the git permission issue
RUN git config --system --add safe.directory "$APP_CODE_PATH"
</code></pre>

<p><a id="the-git-permission-issue"> </a>
</p>
<h5 id="heading-the-git-permission-issue">The <code>git</code> permission issue</h5>
<p>In April 2022,  <a target="_blank" href="https://github.blog/2022-04-12-git-security-vulnerability-announced/">Github accounced the security vulnerability <code>CVE-2022-24765</code></a>, that was fixed in <code>git v2.35.2</code></p>
<blockquote>
<p>This version changes Git’s behavior when looking for a top-level <code>.git</code> directory to stop when 
its directory traversal changes ownership from the current user. </p>
</blockquote>
<p>In practice, the following error occurs if the parent directory is not owned by the user that  executes the <code>git</code> command</p>
<pre><code class="lang-text">Error: fatal: unsafe repository ('/parent/dir/of/.git-folder' is owned by someone else)
To add an exception for this directory, call:

    git config --global --add safe.directory /parent/dir/of/.git-folder
</code></pre>
<p>When using <code>git secret</code>, we would get the slightly misleading error message</p>
<pre><code class="lang-text">git-secret: abort: not in dir with git repo. Use 'git init' or 'git clone', then in repo use 'git secret init'
</code></pre>
<p>We can "fix" the issue by using the new multi-valued  <a target="_blank" href="https://git-scm.com/docs/git-config/2.36.0#Documentation/git-config.txt-safedirectory">safe.directory</a>  configuration via</p>
<pre><code>git config <span class="hljs-operator">-</span><span class="hljs-operator">-</span>system <span class="hljs-operator">-</span><span class="hljs-operator">-</span>add safe.directory <span class="hljs-operator">/</span>parent<span class="hljs-operator">/</span>dir<span class="hljs-operator">/</span>of<span class="hljs-operator">/</span>.git-folder
</code></pre><p>Note, that we didn't use the suggested <code>--global</code> option but <code>--system</code> instead, so that the  configuration is set for <em>any</em> user.</p>
<p>Wait - why not just ensure <strong>that the parent directory of the <code>.git</code> folder has the correct  permissions</strong>?</p>
<p>Well... there's currently (2022-05-28) a <strong>bug in Docker Desktop that makes the permissions of bind  mounts kinda unpredictable</strong>, see  <a target="_blank" href="https://github.com/docker/for-win/issues/12742">Ownership of files set via bind mount is set to user who accesses the file first</a> and by applying the fix directly in the <code>Dockerfile</code> we can solve the issue reliably.</p>

<p><a id="git-secret-usage"> </a>
</p>
<h4 id="heading-git-secret-usage">git-secret usage</h4>

<p><a id="initialize-git-secret"> </a>
</p>
<h5 id="heading-initialize-git-secret">Initialize git-secret</h5>
<p><code>git-secret</code> is initialized via the following command <em>run in the root of the git repository</em></p>
<pre><code class="lang-bash">git secret init
</code></pre>
<pre><code class="lang-text">$ git secret init
git-secret: init created: '/var/www/app/.gitsecret/'
</code></pre>
<p>We only need to do this once, because we'll commit the folder to git later. It contains the following files:</p>
<pre><code class="lang-text">$ git status | grep ".gitsecret"
        new file:   .gitsecret/keys/pubring.kbx
        new file:   .gitsecret/keys/pubring.kbx~
        new file:   .gitsecret/keys/trustdb.gpg
        new file:   .gitsecret/paths/mapping.cfg
</code></pre>
<p>The <code>pubring.kbx~</code> file (with the trailing tilde <code>~</code>) is only a temporary file and can safely be git-ignored. See also <a target="_blank" href="https://github.com/sobolevn/git-secret/issues/566#issuecomment-570059374">Can't find any docs about keyring.kbx~ file</a>.</p>

<p><a id="the-git-secret-directory-and-the-gpg-agent-socket"> </a>
</p>
<h6 id="heading-the-git-secret-directory-and-the-gpg-agent-socket">The <code>git-secret</code> directory and the <code>gpg-agent</code> socket</h6>
<p>To use <code>git-secret</code> in a directory that is <strong>shared between the host system and docker</strong>, we need to  also run the following commands:</p>
<pre><code class="lang-bash">tee .gitsecret/keys/S.gpg-agent &lt;&lt;EOF
%Assuan%
socket=/tmp/S.gpg-agent
EOF

tee .gitsecret/keys/S.gpg-agent.ssh &lt;&lt;EOF
%Assuan%
socket=/tmp/S.gpg-agent.ssh
EOF

tee .gitsecret/keys/gpg-agent.conf &lt;&lt;EOF
extra-socket /tmp/S.gpg-agent.extra
browser-socket /tmp/S.gpg-agent.browser
EOF
</code></pre>
<p>This is necessary because there is an issue <strong>when <code>git-secret</code> is used in a setup where the  codebase is shared between the host system and a docker container</strong>.  I've explained the details in the Github issue <a target="_blank" href="https://github.com/sobolevn/git-secret/issues/806">"gpg: can't connect to the agent: IPC connect call failed" error in docker alpine on shared volume</a>.</p>
<p>In short:</p>
<ul>
<li><code>gpg</code> uses a <code>gpg-agent</code> to perform its tasks and the two tools communicate through sockets 
that are created in the <code>--home-directory</code> of the <code>gpg-agent</code></li>
<li>the agent is started implicitly through a <code>gpg</code> command used by <code>git-secret</code>, using the 
<code>.gitsecret/keys</code> directories as a <code>--home-directory</code></li>
<li>because the location of the <code>--home-directory</code> is shared with the host system, the socket 
creation fails (potentially only an issue for Docker Desktop, see the related discussion in 
Github issue <a target="_blank" href="https://github.com/docker/for-mac/issues/483#issuecomment-647325015">Support for sharing unix sockets</a>)
The corresponding error messages are</li>
</ul>
<pre><code class="lang-text">gpg: can't connect to the agent: IPC connect call failed

gpg-agent: error binding socket to '/var/www/app/.gitsecret/keys/S.gpg-agent': I/O error
</code></pre>
<p>The <strong>workaround for this problem</strong> can be found in  <a target="_blank" href="https://askubuntu.com/a/1053594/1583296">this thread</a>: Configure <code>gpg</code> to use different  locations for the sockets by  <a target="_blank" href="https://github.com/sobolevn/git-secret/issues/806#issuecomment-1084202671">placing additional <code>gpg</code> configuration files in the <code>.gitsecret/keys</code> directory</a>:</p>
<p><strong>S.gpg-agent</strong></p>
<pre><code class="lang-text">%Assuan%
socket=/tmp/S.gpg-agent
</code></pre>
<p><strong>S.gpg-agent.ssh</strong></p>
<pre><code class="lang-text">%Assuan%
socket=/tmp/S.gpg-agent.ssh
</code></pre>
<p><strong>gpg-agent.conf</strong></p>
<pre><code class="lang-text">extra-socket /tmp/S.gpg-agent.extra
browser-socket /tmp/S.gpg-agent.browser
</code></pre>

<p><a id="adding-listing-and-removing-users"> </a>
</p>
<h5 id="heading-adding-listing-and-removing-users">Adding, listing and removing users</h5>
<p>To <strong>add a new user</strong>, you must first <a class="post-section-overview" href="#export-list-and-import-public-gpg-keys">import its public gpg key</a>. Then run:</p>
<pre><code class="lang-bash">email=<span class="hljs-string">"pascal.landau@example.com"</span>
git secret tell <span class="hljs-string">"<span class="hljs-variable">$email</span>"</span>
</code></pre>
<p>In this case, the user <code>pascal.landau@example.com</code> will now be able to decrypt the secrets.</p>
<p>To <strong>show the users</strong> run</p>
<pre><code class="lang-bash">git secret whoknows
</code></pre>
<pre><code class="lang-text">$ git secret whoknows
pascal.landau@example.com
</code></pre>
<p><strong>To remove a user</strong>, run</p>
<pre><code class="lang-bash">email=<span class="hljs-string">"pascal.landau@example.com"</span>
git secret killperson <span class="hljs-string">"<span class="hljs-variable">$email</span>"</span>
</code></pre>
<p>FYI: This command was renamed to <code>removeperson</code> in <code>git-secret &gt;= 0.5.0</code></p>
<pre><code class="lang-text">$ git secret killperson pascal.landau@example.com
git-secret: removed keys.
git-secret: now [pascal.landau@example.com] do not have an access to the repository.
git-secret: make sure to hide the existing secrets again.
</code></pre>
<p>User <code>pascal.landau@example.com</code> will no longer be able to decrypt the secrets.</p>
<p><strong>Caution: The secrets need to be re-encrypted after removing a user!</strong></p>

<p><a id="reminder-rotate-the-encrypted-secrets"> </a>
</p>
<h6 id="heading-reminder-rotate-the-encrypted-secrets">Reminder: Rotate the encrypted secrets</h6>
<p>Please be aware that <strong>not only your secrets are stored in git, but who had access as well</strong>. I.e.  even if you remove a user and re-encrypt the secrets, that user would <strong>still be able to decrypt  the secrets of a previous commit</strong> (when the user was still added). In consequence, <strong>you need  to rotate the encrypted secrets themselves as well after removing a user</strong>.</p>
<p>But isn't that a great flaw in the system, making it a bad idea to use <code>git-secret</code> in general? </p>
<p>In my opinion: No. </p>
<p>If the removed user had access to the secrets at <strong>any</strong> point in time (no  matter where they have been stored), he could very well have just created a local copy or simply  "written them down". In terms of security there is really no "added downside" due to <code>git-secret</code>. It just makes it <em>very</em> clear that you <em>must</em> rotate the secrets ¯\_(ツ)_/¯</p>
<p>See also this  <a target="_blank" href="https://news.ycombinator.com/item?id=11663403">lengthy discussion on <code>git-secret</code> on Hacker News</a>.</p>

<p><a id="adding-listing-and-removing-files-for-encryption"> </a>
</p>
<h5 id="heading-adding-listing-and-removing-files-for-encryption">Adding, listing and removing files for encryption</h5>
<p>Run <code>git secret add [filenames...]</code> for <strong>files you want to encrypt</strong>. Example:</p>
<pre><code class="lang-bash">git secret add .env
</code></pre>
<p>If <code>.env</code> is not added in <code>.gitignore</code>, <code>git-secret</code> will display a warning and add it  automatically.</p>
<pre><code class="lang-text">git-secret: these files are not in .gitignore: .env
git-secret: auto adding them to .env
git-secret: 1 item(s) added.
</code></pre>
<p>Otherwise, the file is added with no warning.</p>
<pre><code class="lang-text">$ git secret add .env
git-secret: 1 item(s) added.
</code></pre>
<p>You only need to add files once. They are then stored in <code>.gitsecret/paths/mapping.cfg</code>:</p>
<pre><code class="lang-text">$ cat .gitsecret/paths/mapping.cfg
.env:505070fc20233cb426eac6a3414399d0f466710c993198b1088e897fdfbbb2d5
</code></pre>
<p>You can also show the added files via</p>
<pre><code class="lang-bash">git secret list
</code></pre>
<pre><code class="lang-text">$ git secret list
.env
</code></pre>
<p><strong>Caution: The files are not yet encrypted!</strong></p>
<p>If you want to <strong>remove a file from being encrypted</strong>, run</p>
<pre><code class="lang-bash">git secret remove .env
</code></pre>
<p>Output</p>
<pre><code class="lang-text">$ git secret remove .env
git-secret: removed from index.
git-secret: ensure that files: [.env] are now not ignored.
</code></pre>

<p><a id="encrypt-files"> </a>
</p>
<h5 id="heading-encrypt-files">Encrypt files</h5>
<p>To actually <strong>encrypt the files</strong>, run:</p>
<pre><code class="lang-bash">git secret hide
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">$ git secret hide
git-secret: done. 1 of 1 files are hidden.
</code></pre>
<p>The encrypted (binary) file is stored at <code>$filename.secret</code>, i.e. <code>.env.secret</code> in this case:</p>
<pre><code class="lang-text">$ cat .env.secret
�☺♀♥�H~�B�Ӯ☺�"��▼♂F�►���l�Cs��S�@MHWs��e������{♣♫↕↓�L� ↕s�1�J$◄♥�;���ǆ֕�Za�����\u�ٲ&amp; ¶��V�► ���6��
;&lt;�d:��}ҨD%.�;��&amp;��G����vWW�]&gt;���߶��▲;D�+Rs�S→�Y!&amp;J��۪8���ٔF��→f����*��$♠���&amp;RC�8▼♂�☻z h��Z0M�T&gt;
</code></pre>
<p>The encrypted files are de-cryptable <strong>for all users that have been added via <code>git secret tell</code></strong>.  That also means that you need to <strong>run this command again whenever a new user is added</strong>.</p>

<p><a id="decrypting-files"> </a>
</p>
<h5 id="heading-decrypting-files">Decrypting files</h5>
<p>You can <strong>decrypt files</strong> via</p>
<pre><code class="lang-bash">git secret reveal
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">$ git secret reveal
File '/var/www/app/.env' exists. Overwrite? (y/N) y
git-secret: done. 1 of 1 files are revealed.
</code></pre>
<ul>
<li>the files are decrypted and will overwrite the current, unencrypted files (if they already exist)<ul>
<li>use the <code>-f</code> option to force the overwrite and run non-interactively</li>
</ul>
</li>
<li>if you only want to check the content of an encrypted file, you can use
<code>git secret cat $filename</code> (e.g. <code>git secret cat .env</code>)</li>
</ul>
<p>In case the secret <code>gpg</code> key is password protected, you must pass the password  <a target="_blank" href="https://git-secret.io/git-secret-reveal">via the <code>-p</code> option</a>. E.g. for password <code>123456</code></p>
<pre><code class="lang-bash">git secret reveal -p 123456
</code></pre>

<p><a id="show-changes-between-encrypted-and-decrypted-files"> </a>
</p>
<h5 id="heading-show-changes-between-encrypted-and-decrypted-files">Show changes between encrypted and decrypted files</h5>
<p>One problem that comes with encrypted files: <strong>You can't review them during a code review in a remote tool</strong>. So in order to understand what changes have been made, it is helpful to
<strong>show the changes between the encrypted and the decrypted files</strong>. This can be done via</p>
<pre><code class="lang-bash">git secret changes
</code></pre>
<p>Output:</p>
<pre><code class="lang-text">$ echo "foo" &gt;&gt; .env
$ git secret changes
git-secret: changes in /var/www/app/.env:
--- /dev/fd/63
+++ /var/www/app/.env
@@ -34,3 +34,4 @@
 MAIL_ENCRYPTION=null
 MAIL_FROM_ADDRESS=null
 MAIL_FROM_NAME="${APP_NAME}"
+foo
</code></pre>
<p>Note the <code>+foo</code> at the bottom of the output. It was added in the first line via  <code>echo "foo"&gt; &gt;&gt; .env</code>.</p>

<p><a id="makefile-adjustments"> </a>
</p>
<h2 id="heading-makefile-adjustments">Makefile adjustments</h2>
<p>Since I won't be able to remember all the commands for <code>git-secret</code> and <code>gpg</code>, I've added them to the Makefile at <code>.make/01-00-application-setup.mk</code>:</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># File: .make/01-00-application-setup.mk</span>

<span class="hljs-comment">#...</span>

<span class="hljs-comment"># gpg</span>

DEFAULT_SECRET_GPG_KEY?=secret.gpg
DEFAULT_PUBLIC_GPG_KEYS?=.dev/gpg-keys/*

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg</span>
<span class="hljs-section">gpg: ## Run gpg commands. Specify the command e.g. via ARGS="--list-keys"</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> gpg <span class="hljs-variable">$(ARGS)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-export-public-key</span>
<span class="hljs-section">gpg-export-public-key: ## Export a gpg public key e.g. via EMAIL="john.doe@example.com" PATH=".dev/gpg-keys/john-public.gpg"</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(PATH)</span>,,$(<span class="hljs-built_in">error</span> PATH is undefined)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(EMAIL)</span>,,$(<span class="hljs-built_in">error</span> EMAIL is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg ARGS=<span class="hljs-string">"gpg --armor --export <span class="hljs-variable">$(EMAIL)</span> &gt; <span class="hljs-variable">$(PATH)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-export-private-key</span>
<span class="hljs-section">gpg-export-private-key: ## Export a gpg private key e.g. via EMAIL="john.doe@example.com" PATH="secret.gpg"</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(PATH)</span>,,$(<span class="hljs-built_in">error</span> PATH is undefined)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(EMAIL)</span>,,$(<span class="hljs-built_in">error</span> EMAIL is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg ARGS=<span class="hljs-string">"--output <span class="hljs-variable">$(PATH)</span> --armor --export-secret-key <span class="hljs-variable">$(EMAIL)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import</span>
<span class="hljs-section">gpg-import: ## Import a gpg key file e.g. via GPG_KEY_FILES="/path/to/file /path/to/file2"</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(GPG_KEY_FILES)</span>,,$(<span class="hljs-built_in">error</span> GPG_KEY_FILES is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg ARGS=<span class="hljs-string">"--import --batch --yes --pinentry-mode loopback <span class="hljs-variable">$(GPG_KEY_FILES)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import-default-secret-key</span>
<span class="hljs-section">gpg-import-default-secret-key: ## Import the default secret key</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg-import GPG_KEY_FILES=<span class="hljs-string">"<span class="hljs-variable">$(DEFAULT_SECRET_GPG_KEY)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import-default-public-keys</span>
<span class="hljs-section">gpg-import-default-public-keys: ## Import the default public keys</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg-import GPG_KEY_FILES=<span class="hljs-string">"<span class="hljs-variable">$(DEFAULT_PUBLIC_GPG_KEYS)</span>"</span> 

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-init</span>
<span class="hljs-section">gpg-init: gpg-import-default-secret-key gpg-import-default-public-keys ## Initialize gpg in the container, i.e. import all public and private keys</span>

<span class="hljs-comment"># git-secret</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: git-secret</span>
<span class="hljs-section">git-secret: ## Run git-secret commands. Specify the command e.g. via ARGS="hide"</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> git-secret <span class="hljs-variable">$(ARGS)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-init</span>
<span class="hljs-section">secret-init: ## Initialize git-secret in the repository via `git-secret init`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"init"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-init-gpg-socket-config</span>
<span class="hljs-section">secret-init-gpg-socket-config: ## Initialize the config files to change the gpg socket locations</span>
    echo <span class="hljs-string">"%Assuan%"</span> &gt; .gitsecret/keys/S.gpg-agent
    echo <span class="hljs-string">"socket=/tmp/S.gpg-agent"</span> &gt;&gt; .gitsecret/keys/S.gpg-agent
    echo <span class="hljs-string">"%Assuan%"</span> &gt; .gitsecret/keys/S.gpg-agent.ssh
    echo <span class="hljs-string">"socket=/tmp/S.gpg-agent.ssh"</span> &gt;&gt; .gitsecret/keys/S.gpg-agent.ssh
    echo <span class="hljs-string">"extra-socket /tmp/S.gpg-agent.extra"</span> &gt; .gitsecret/keys/gpg-agent.conf
    echo <span class="hljs-string">"browser-socket /tmp/S.gpg-agent.browser"</span> &gt;&gt; .gitsecret/keys/gpg-agent.conf

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-encrypt</span>
<span class="hljs-section">secret-encrypt: ## Decrypt secret files via `git-secret hide`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"hide"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-decrypt</span>
<span class="hljs-section">secret-decrypt: ## Decrypt secret files via `git-secret reveal -f`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"reveal -f"</span> 

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-decrypt-with-password</span>
<span class="hljs-section">secret-decrypt-with-password: ## Decrypt secret files using a password for gpg via `git-secret reveal -f -p <span class="hljs-variable">$(GPG_PASSWORD)</span>`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(GPG_PASSWORD)</span>,,$(<span class="hljs-built_in">error</span> GPG_PASSWORD is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"reveal -f -p <span class="hljs-variable">$(GPG_PASSWORD)</span>"</span> 

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-add</span>
<span class="hljs-section">secret-add: ## Add a file to git secret via `git-secret add $FILE`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(FILE)</span>,,$(<span class="hljs-built_in">error</span> FILE is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"add <span class="hljs-variable">$(FILE)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-cat</span>
<span class="hljs-section">secret-cat: ## Show the contents of file to git secret via `git-secret cat $FILE`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(FILE)</span>,,$(<span class="hljs-built_in">error</span> FILE is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"cat <span class="hljs-variable">$(FILE)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-list</span>
<span class="hljs-section">secret-list: ## List all files added to git secret `git-secret list`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"list"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-remove</span>
<span class="hljs-section">secret-remove: ## Remove a file from git secret via `git-secret remove $FILE`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(FILE)</span>,,$(<span class="hljs-built_in">error</span> FILE is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"remove <span class="hljs-variable">$(FILE)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-add-user</span>
<span class="hljs-section">secret-add-user: ## Remove a user from git secret via `git-secret tell $EMAIL`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(EMAIL)</span>,,$(<span class="hljs-built_in">error</span> EMAIL is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"tell <span class="hljs-variable">$(EMAIL)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-show-users</span>
<span class="hljs-section">secret-show-users: ## Show all users that have access to git secret via `git-secret whoknows`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"whoknows"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-remove-user</span>
<span class="hljs-section">secret-remove-user: ## Remove a user from git secret via `git-secret killperson $EMAIL`</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(EMAIL)</span>,,$(<span class="hljs-built_in">error</span> EMAIL is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"killperson <span class="hljs-variable">$(EMAIL)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: secret-diff</span>
<span class="hljs-section">secret-diff: ## Show the diff between the content of encrypted and decrypted files via `git-secret changes`</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s git-secret ARGS=<span class="hljs-string">"changes"</span>
</code></pre>

<p><a id="workflow"> </a>
</p>
<h2 id="heading-workflow">Workflow</h2>
<p>Working with <code>git-secret</code> is pretty straight forward:</p>
<ul>
<li>initialize <code>git-secret</code></li>
<li>add all users</li>
<li>add all secret files and make sure they are ignored via <code>.gitignore</code></li>
<li>encrypt the files</li>
<li>commit the encrypted files like "any other file"</li>
<li>if any changes were made by other team members to the files:<ul>
<li>=&gt; decrypt to get the most up-to-date ones</li>
</ul>
</li>
<li>if any modifications are required from your side:<ul>
<li>=&gt; make the changes to the decrypted files and then re-encrypt them again</li>
</ul>
</li>
</ul>
<p>But: The devil is in the details. The <a class="post-section-overview" href="#process-challenges">Process challenges</a> section explains some of the pitfalls that we have encountered and the <a class="post-section-overview" href="#scenarios">Scenarios</a> section gives some concrete examples for common scenarios.</p>

<p><a id="process-challenges"> </a>
</p>
<h3 id="heading-process-challenges">Process challenges</h3>
<p>From a process perspective we've encountered some challenges that I'd like to mention - including how we deal with them.</p>

<p><a id="updating-secrets"> </a>
</p>
<h4 id="heading-updating-secrets">Updating secrets</h4>
<p>When updating secrets you must ensure to always <strong>decrypt the files first</strong> in order to avoid using "stale" files that you might still have locally. I usually check out the latest <code>main</code> branch and run <code>git secret reveal</code> to have the most up-to-date versions of the secret files. You  could also use a <a target="_blank" href="https://stackoverflow.com/a/4185449/413531"><code>post-merge</code> git hook</a> to do  this automatically, but I personally don't want to risk overwriting my local secret files by  accident.</p>

<p><a id="code-reviews-and-merge-conflicts"> </a>
</p>
<h4 id="heading-code-reviews-and-merge-conflicts">Code reviews and merge conflicts</h4>
<p>Since the <strong>encrypted files cannot be diffed meaningfully</strong>, the code reviews become more difficult when secrets are involved. We use Gitlab for reviews and I usually first check the diff of the <code>.gitsecret/paths/mapping.cfg</code> file to see "which files have changed" directly in the UI.</p>
<p>In addition, I will</p>
<ul>
<li>checkout the <code>main</code> branch</li>
<li>decrypt the secrets via <code>git secret reveal -f</code></li>
<li>checkout the <code>feature-branch</code></li>
<li>run <code>git secret changes</code> to see the differences between the decrypted files from <code>main</code> and the
encrypted files from <code>feature-branch</code></li>
</ul>
<p>Things get even more complicated when multiple team members need to modify secret files at the same time on different branches, as <strong>the encrypted files cannot be compared - i.e. git cannot be smart  about delta updates</strong>. The only way around this is coordinating the pull requests, i.e. merge the first, update the secrets of the second and then merge the second.</p>
<p>Fortunately, this has only happened very rarely so far.</p>

<p><a id="local-git-secret-and-gpg-setup"> </a>
</p>
<h4 id="heading-local-git-secret-and-gpg-setup">Local <code>git-secret</code> and <code>gpg</code> setup</h4>
<p>Currently, all developers in our team have <code>git-secret</code> installed locally (instead of using it through docker) and use their own <code>gpg</code> keys.</p>
<p>This means more onboarding overhead, because</p>
<ul>
<li>a new dev must<ul>
<li>install <code>git-secret</code> locally (*)</li>
<li>install and setup <code>gpg</code> locally (*)</li>
<li>create a <code>gpg</code> key pair</li>
</ul>
</li>
<li>the public key must be added by every other team member (*)</li>
<li>the user of the key must be added via <code>git secret tell</code></li>
<li>the secrets must be re-encrypted</li>
</ul>
<p>And for offboarding</p>
<ul>
<li>the public key must be removed by every other team member (*)</li>
<li>the user of the key must be removed via <code>git secret killperson</code></li>
<li>the secrets must be re-encrypted</li>
</ul>
<p>Plus, we need to ensure that the <code>git-secret</code> and <code>gpg</code> versions are kept up-to-date for everyone to not run into any compatibility issues.</p>
<p>As an alternative, I'm currently leaning more towards <strong>handling everything through docker</strong> (as presented in this tutorial). All steps marked with (*) are then obsolete, i.e. there is no need  to setup <code>git-secret</code> and <code>gpg</code> locally. </p>
<p>But the approach also comes with some downsides, because</p>
<ul>
<li>the <strong>secret key and all public keys have to be imported every time the container is started</strong></li>
<li><strong>each dev needs to put his private <code>gpg</code> key "in the codebase"</strong> (ignored by <code>.gitignore</code>) so it 
can be shared with docker and imported by <code>gpg</code> (in docker). The alternative would be using 
a single secret key that is   shared within the team - which feels very wrong :P</li>
</ul>
<p>To make this a little more convenient, <strong>we put the public gpg keys of every dev in the  repository</strong> under <code>.dev/gpg-keys/</code> and <strong>the private key has to be named <code>secret.gpg</code> and put  in the root of the codebase</strong>. </p>
<p>In this setup, <code>secret.gpg</code> must also be added to the<code>.gitignore</code> file. </p>
<pre><code class="lang-gitignore"># File: .gitignore
#...
vendor/
secret.gpg
</code></pre>
<p>The import can now be simplified with <code>make</code> targets:</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># gpg</span>

DEFAULT_SECRET_GPG_KEY?=secret.gpg
DEFAULT_PUBLIC_GPG_KEYS?=.dev/gpg-keys/*

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg</span>
<span class="hljs-section">gpg: ## Run gpg commands. Specify the command e.g. via ARGS="--list-keys"</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> gpg <span class="hljs-variable">$(ARGS)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import</span>
<span class="hljs-section">gpg-import: ## Import a gpg key file e.g. via GPG_KEY_FILES="/path/to/file /path/to/file2"</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(GPG_KEY_FILES)</span>,,$(<span class="hljs-built_in">error</span> GPG_KEY_FILES is undefined)</span>)
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg ARGS=<span class="hljs-string">"--import --batch --yes --pinentry-mode loopback <span class="hljs-variable">$(GPG_KEY_FILES)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import-default-secret-key</span>
<span class="hljs-section">gpg-import-default-secret-key: ## Import the default secret key</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg-import GPG_KEY_FILES=<span class="hljs-string">"<span class="hljs-variable">$(DEFAULT_SECRET_GPG_KEY)</span>"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-import-default-public-keys</span>
<span class="hljs-section">gpg-import-default-public-keys: ## Import the default public keys</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -s gpg-import GPG_KEY_FILES=<span class="hljs-string">"<span class="hljs-variable">$(DEFAULT_PUBLIC_GPG_KEYS)</span>"</span> 

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: gpg-init</span>
<span class="hljs-section">gpg-init: gpg-import-default-secret-key gpg-import-default-public-keys ## Initialize gpg in the container, i.e. import all public and private keys</span>
</code></pre>
<p>"Everything" can now be handled via </p>
<pre><code class="lang-bash">make gpg-init
</code></pre>
<p>that needs to be run one single time after a container has been started.</p>

<p><a id="scenarios"> </a>
</p>
<h3 id="heading-scenarios">Scenarios</h3>
<p>The scenarios assume the following preconditions:</p>
<ul>
<li>You have checked out branch <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/git-secret-encrypt-repository-docker">part-6-git-secret-encrypt-repository-docker</a><pre><code class="lang-bash">git checkout part-6-git-secret-encrypt-repository-docker
</code></pre>
and no running docker containers <pre><code class="lang-bash">make docker-down
</code></pre>
</li>
<li>You have deleted the existing <code>git-secret</code> folder, the keys in <code>.dev/gpg-keys</code>, the 
<code>secret.gpg</code> key and the <code>passwords.*</code> files <pre><code class="lang-bash">rm -rf .gitsecret/ .dev/gpg-keys/* secret.gpg passwords.*
</code></pre>
</li>
</ul>

<p><a id="initial-setup-of-gpg-keys"> </a>
</p>
<h4 id="heading-initial-setup-of-gpg-keys">Initial setup of <code>gpg</code> keys</h4>
<p>Unfortunately, I didn't find a way to create and export <code>gpg</code> keys through <code>make</code> and <code>docker</code>. You need to either run the commands interactively OR pass a string with newlines to it. Both things are horribly complicated with <code>make</code> and docker. Thus, you need to log into the <code>application</code> container and run the commands in there directly. Not great - but this needs to be done only once when a new developer is onboarded anyways.</p>
<p>FYI: I usually log into containers via <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#easy-container-access-via-din-bashrc-helper">Easy container access via din .bashrc helper</a>.</p>
<p>The secret key is exported to <code>secret.gpg</code> and the public key to <code>.dev/gpg-keys/alice-public.gpg</code>.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># start the docker setup</span>
make docker-up

<span class="hljs-comment"># log into the container ('winpty' is only required on Windows)</span>
winpty docker <span class="hljs-built_in">exec</span> -ti dofroscra_local-application-1 bash

<span class="hljs-comment"># export key pair</span>
name=<span class="hljs-string">"Alice Doe"</span>
email=<span class="hljs-string">"alice@example.com"</span>
gpg --batch --gen-key &lt;&lt;EOF
Key-Type: 1
Key-Length: 2048
Subkey-Type: 1
Subkey-Length: 2048
Name-Real: <span class="hljs-variable">$name</span>
Name-Email: <span class="hljs-variable">$email</span>
Expire-Date: 0
%no-protection
EOF

<span class="hljs-comment"># export the private key</span>
gpg --output secret.gpg --armor --export-secret-key <span class="hljs-variable">$email</span>

<span class="hljs-comment"># export the public key</span>
gpg --armor --<span class="hljs-built_in">export</span> <span class="hljs-variable">$email</span> &gt; .dev/gpg-keys/alice-public.gpg
</code></pre>
<pre><code class="lang-text">$ make docker-up
ENV=local TAG=latest DOCKER_REGISTRY=docker.io DOCKER_NAMESPACE=dofroscra APP_USER_NAME=application APP_GROUP_NAME=application docker compose -p dofroscra_local --env-file ./.docker/.env -f ./.docker/docker-compose/docker-compose.yml -f ./.docker/docker-compose/docker-compose.local.yml up -d
Container dofroscra_local-application-1  Created
...
Container dofroscra_local-application-1  Started
$ docker ps
CONTAINER ID   IMAGE                                COMMAND                  CREATED          STATUS          PORTS                NAMES
...
95f740607586   dofroscra/application-local:latest   "/usr/sbin/sshd -D"      21 minutes ago   Up 21 minutes   0.0.0.0:2222-&gt;22/tcp dofroscra_local-application-1

$ winpty docker exec -ti dofroscra_local-application-1 bash
root:/var/www/app# name="Alice Doe"
root:/var/www/app# email="alice@example.com"
gpg --batch --gen-key &lt;&lt;EOF
Key-Type: 1
Key-Length: 2048
Subkey-Type: 1
Subkey-Length: 2048
Name-Real: $name
Name-Email: $email
Expire-Date: 0
%no-protection
EOF
root:/var/www/app# gpg --batch --gen-key &lt;&lt;EOF
&gt; Key-Type: 1
&gt; Key-Length: 2048
&gt; Subkey-Type: 1
&gt; Subkey-Length: 2048
&gt; Name-Real: $name
&gt; Name-Email: $email
&gt; Expire-Date: 0
&gt; %no-protection
&gt; EOF
gpg: directory '/root/.gnupg' created
gpg: keybox '/root/.gnupg/pubring.kbx' created
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key BBBE654440E720C1 marked as ultimately trusted
gpg: directory '/root/.gnupg/openpgp-revocs.d' created
gpg: revocation certificate stored as '/root/.gnupg/openpgp-revocs.d/225C736E0E70AC222C072B70BBBE654440E720C1.rev'

root:/var/www/app# gpg --output secret.gpg --armor --export-secret-key $email
root:/var/www/app# head secret.gpg
-----BEGIN PGP PRIVATE KEY BLOCK-----

lQOYBGJD+bwBCADBGKySV5PINc5MmQB3PNvCG7Oa1VMBO8XJdivIOSw7ykv55PRP
3g3R+ERd1Ss5gd5KAxLc1tt6PHGSPTypUJjCng2plwD8Jy5A/cC6o2x8yubOslLa
x1EC9fpcxUYUNXZavtEr+ylOaTaRz6qwSabsAgkg2NZ0ey/QKmFOZvhL8NlK9lTI
GgZPTiqPCsr7hiNg0WRbT5h8nTmfpl/DdTgwfPsDn5Hn0TEMa79WsrPnnq16jsq0
Uusuw3tOmdSdYnT8j7m1cpgcSj0hRF1eh4GVE0o62GqeLTWW9mfpcuv7n6mWaCB8
DCH6H238gwUriq/aboegcuBktlvSY21q/MIXABEBAAEAB/wK/M2buX+vavRgDRgR
hjUrsJTXO3VGLYcIetYXRhLmHLxBriKtcBa8OxLKKL5AFEuNourOBdcmTPiEwuxH
5s39IQOTrK6B1UmUqXvFLasXghorv8o8KGRL4ABM4Bgn6o+KBAVLVIwvVIhQ4rlf

root:/var/www/app# gpg --armor --export $email &gt; .dev/gpg-keys/alice-public.gpg
root:/var/www/app# head .dev/gpg-keys/alice-public.gpg
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQENBGJD+bwBCADBGKySV5PINc5MmQB3PNvCG7Oa1VMBO8XJdivIOSw7ykv55PRP
3g3R+ERd1Ss5gd5KAxLc1tt6PHGSPTypUJjCng2plwD8Jy5A/cC6o2x8yubOslLa
x1EC9fpcxUYUNXZavtEr+ylOaTaRz6qwSabsAgkg2NZ0ey/QKmFOZvhL8NlK9lTI
GgZPTiqPCsr7hiNg0WRbT5h8nTmfpl/DdTgwfPsDn5Hn0TEMa79WsrPnnq16jsq0
Uusuw3tOmdSdYnT8j7m1cpgcSj0hRF1eh4GVE0o62GqeLTWW9mfpcuv7n6mWaCB8
DCH6H238gwUriq/aboegcuBktlvSY21q/MIXABEBAAG0HUFsaWNlIERvZSA8YWxp
Y2VAZXhhbXBsZS5jb20+iQFOBBMBCgA4FiEEIlxzbg5wrCIsBytwu75lREDnIMEF
AmJD+bwCGy8FCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQu75lREDnIMEN4Af+
</code></pre>
<p>That's it. We now have a new secret and private key for <code>alice@example.com</code> and have exported it to  <code>secret.gpg</code> resp. <code>.dev/gpg-keys/alice-public.gpg</code> (and thus shared it with the host system).  The remaining commands can now be run outside of the <code>application</code> container directly on the  host system.</p>

<p><a id="initial-setup-of-git-secret"> </a>
</p>
<h4 id="heading-initial-setup-of-git-secret">Initial setup of <code>git-secret</code></h4>
<p>Let's say we want to introduce <code>git-secret</code> "from scratch" to a new codebase. Then you would run  the following commands:</p>
<p><strong>Initialize <code>git-secret</code></strong></p>
<pre><code class="lang-bash">make secret-init
</code></pre>
<pre><code class="lang-text">$ make secret-init
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="init";
git-secret: init created: '/var/www/app/.gitsecret/'
</code></pre>
<p><strong>Apply the <code>gpg</code> fix for shared directories</strong></p>
<p>See <a class="post-section-overview" href="#the-git-secret-directory-and-the-gpg-agent-socket">The <code>git-secret</code> directory and the <code>gpg-agent</code> socket</a>.</p>
<pre><code class="lang-bash">$ make secret-init-gpg-socket-config
</code></pre>
<pre><code class="lang-text">$ make secret-init-gpg-socket-config
echo "%Assuan%" &gt; .gitsecret/keys/S.gpg-agent
echo "socket=/tmp/S.gpg-agent" &gt;&gt; .gitsecret/keys/S.gpg-agent
echo "%Assuan%" &gt; .gitsecret/keys/S.gpg-agent.ssh
echo "socket=/tmp/S.gpg-agent.ssh" &gt;&gt; .gitsecret/keys/S.gpg-agent.ssh
echo "extra-socket /tmp/S.gpg-agent.extra" &gt; .gitsecret/keys/gpg-agent.conf
echo "browser-socket /tmp/S.gpg-agent.browser" &gt;&gt; .gitsecret/keys/gpg-agent.conf
</code></pre>

<p><a id="initialize-gpg-after-container-startup"> </a>
</p>
<h4 id="heading-initialize-gpg-after-container-startup">Initialize <code>gpg</code> after container startup</h4>
<p>After restarting the containers, we need to initialize <code>gpg</code>, i.e. import all public keys from  <code>.dev/gpg-keys/*</code> and the private key from <code>secret.gpg</code>. Otherwise we will not be able to en-  and decrypt the files.</p>
<pre><code class="lang-bash">make gpg-init
</code></pre>
<pre><code class="lang-text">$ make gpg-init
"C:/Program Files/Git/mingw64/bin/make" -s gpg-import GPG_KEY_FILES="secret.gpg"
gpg: directory '/home/application/.gnupg' created
gpg: keybox '/home/application/.gnupg/pubring.kbx' created
gpg: /home/application/.gnupg/trustdb.gpg: trustdb created
gpg: key BBBE654440E720C1: public key "Alice Doe &lt;alice@example.com&gt;" imported
gpg: key BBBE654440E720C1: secret key imported
gpg: Total number processed: 1
gpg:               imported: 1
gpg:       secret keys read: 1
gpg:   secret keys imported: 1
"C:/Program Files/Git/mingw64/bin/make" -s gpg-import GPG_KEY_FILES=".dev/gpg-keys/*"
gpg: key BBBE654440E720C1: "Alice Doe &lt;alice@example.com&gt;" not changed
gpg: Total number processed: 1
gpg:              unchanged: 1
</code></pre>

<p><a id="adding-new-team-members"> </a>
</p>
<h4 id="heading-adding-new-team-members">Adding (new) team members</h4>
<p>Let's start by adding our own user to <code>git-secret</code></p>
<pre><code class="lang-bash">make secret-add-user EMAIL=<span class="hljs-string">"alice@example.com"</span>
</code></pre>
<pre><code class="lang-text">$ make secret-add-user EMAIL="alice@example.com"
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="tell alice@example.com"
git-secret: done. alice@example.com added as user(s) who know the secret.
</code></pre>
<p>And verify that it worked via</p>
<pre><code class="lang-bash">make secret-show-users
</code></pre>
<pre><code class="lang-text">$ make secret-show-users
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="whoknows"
alice@example.com
</code></pre>

<p><a id="adding-and-encrypting-files"> </a>
</p>
<h4 id="heading-adding-and-encrypting-files">Adding and encrypting files</h4>
<p>Let's add a new encrypted file <code>secret_password.txt</code>.</p>
<p>Create the file </p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"my_new_secret_password"</span> &gt; secret_password.txt
</code></pre>
<p>Add it to <code>.gitignore</code></p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"secret_password.txt"</span> &gt;&gt; .gitignore
</code></pre>
<p>Add it to <code>git-secret</code></p>
<pre><code class="lang-bash">make secret-add FILE=<span class="hljs-string">"secret_password.txt"</span>
</code></pre>
<pre><code class="lang-text">$ make secret-add FILE="secret_password.txt"
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="add secret_password.txt"
git-secret: 1 item(s) added.
</code></pre>
<p>Encrypt all files</p>
<pre><code class="lang-bash">make secret-encrypt
</code></pre>
<pre><code class="lang-text">$ make secret-encrypt
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="hide"
git-secret: done. 1 of 1 files are hidden.

$ ls secret_password.txt.secret
secret_password.txt.secret
</code></pre>

<p><a id="decrypt-files"> </a>
</p>
<h4 id="heading-decrypt-files">Decrypt files</h4>
<p>Let's first remove the "plain" <code>secret_password.txt</code> file</p>
<pre><code class="lang-bash">rm secret_password.txt
</code></pre>
<pre><code class="lang-text">$ rm secret_password.txt

$ ls secret_password.txt
ls: cannot access 'secret_password.txt': No such file or directory
</code></pre>
<p>and then decrypt the encrypted one.</p>
<pre><code class="lang-bash">make secret-decrypt
</code></pre>
<pre><code class="lang-text">$ make secret-decrypt
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="reveal -f"
git-secret: done. 1 of 1 files are revealed.

$ cat secret_password.txt
my_new_secret_password
</code></pre>
<p><strong>Caution:</strong> If the secret <code>gpg</code> key is password protected (e.g. <code>123456</code>), run</p>
<pre><code class="lang-bash">make secret-decrypt-with-password GPG_PASSWORD=123456
</code></pre>
<p>You could also add the <code>GPG_PASSWORD</code> variable to the  <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/#shared-variables-make-env"><code>.make/.env</code></a> file as a local default value so that you wouldn't have to specify the value every time and  could then simply run</p>
<pre><code class="lang-bash">make secret-decrypt-with-password
</code></pre>
<p>without passing <code>GPG_PASSWORD</code></p>

<p><a id="removing-files"> </a>
</p>
<h4 id="heading-removing-files">Removing files</h4>
<p>Remove the <code>secret_password.txt</code> file we added previously:</p>
<pre><code class="lang-bash">make secret-remove FILE=<span class="hljs-string">"secret_password.txt"</span>
</code></pre>
<pre><code class="lang-text">$ make secret-remove FILE="secret_password.txt"
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="remove secret_password.txt"
git-secret: removed from index.
git-secret: ensure that files: [secret_password.txt] are now not ignored.
</code></pre>
<p><strong>Caution: this will neither remove the <code>secret_password.txt</code> file nor  the <code>secret_password.txt.secret</code> file automatically"</strong></p>
<pre><code class="lang-text">$ ls -l | grep secret_password.txt
-rw-r--r-- 1 Pascal 197121     19 Mar 31 14:03 secret_password.txt
-rw-r--r-- 1 Pascal 197121    358 Mar 31 14:02 secret_password.txt.secret
</code></pre>
<p>But even though the encrypted <code>secret_password.txt.secret</code> file still exists, it will not be  decrypted:</p>
<pre><code class="lang-text">$ make secret-decrypt
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="reveal -f"
git-secret: done. 0 of 0 files are revealed.
</code></pre>

<p><a id="removing-team-members"> </a>
</p>
<h4 id="heading-removing-team-members">Removing team members</h4>
<p>Removing a team member can be done via</p>
<pre><code class="lang-bash">make secret-remove-user EMAIL=<span class="hljs-string">"alice@example.com"</span>
</code></pre>
<pre><code class="lang-text">$ make secret-remove-user EMAIL="alice@example.com"
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="killperson alice@example.com"
git-secret: removed keys.
git-secret: now [alice@example.com] do not have an access to the repository.
git-secret: make sure to hide the existing secrets again.
</code></pre>
<p>If there are any users left, we must make sure to re-encrypt the secrets via</p>
<pre><code class="lang-bash">make secret-encrypt
</code></pre>
<p>Otherwise (if no more users are left) <code>git-secret</code> would simply error out</p>
<pre><code class="lang-text">$ make secret-decrypt
"C:/Program Files/Git/mingw64/bin/make" -s git-secret ARGS="reveal -f"
git-secret: abort: no public keys for users found. run 'git secret tell email@address'.
make[1]: *** [.make/01-00-application-setup.mk:57: git-secret] Error 1
make: *** [.make/01-00-application-setup.mk:69: secret-decrypt] Error 2
</code></pre>
<p><strong>Caution</strong>: Please keep in mind to  <a class="post-section-overview" href="#reminder-rotate-the-encrypted-secrets">rotate the secrets themselves as well</a>!</p>

<p><a id="pros-and-cons"> </a>
</p>
<h2 id="heading-pros-and-cons">Pros and cons</h2>

<p><a id="pro"> </a>
</p>
<h3 id="heading-pro">Pro</h3>
<ul>
<li>very low barrier to entry:<ul>
<li>no third party service required</li>
<li>easy to integrate in existing codebases, because the secrets are located directly in 
the codebase</li>
<li>everything can be handled through docker (no additional local software necessary)</li>
</ul>
</li>
<li>once set up, it is very easy/convenient to use and can be integrated in a team workflow</li>
<li>changes to secrets can be reviewed before they are merged<ul>
<li>this leads to less fuck-ups on deployments</li>
</ul>
</li>
<li>"everything" is in the repository, which brings a lot of familiar benefits like<ul>
<li>version control</li>
<li>a single <code>git pull</code> is the only thing you need to get everything (=&gt; good dev experience)</li>
</ul>
</li>
</ul>

<p><a id="cons"> </a>
</p>
<h3 id="heading-cons">Cons</h3>
<ul>
<li>some overhead during onboarding and offboarding</li>
<li>the secret key must be put in the root of the repository at <code>./secret.gpg</code></li>
<li>no fine grained permissions for different secrets, e.g. the mysql password on production and 
staging can not be treated differently<ul>
<li>if somebody can decrypt secrets, ALL of them are exposed</li>
</ul>
</li>
<li>if the a secret key ever gets leaked, all secrets are compromised<ul>
<li>=&gt; can be mitigated (to a degree) by using a passphrase on the secret key</li>
<li>=&gt; this is kinda true for any other system that stores secrets as well BUT third parties 
could probably implement additional measures like multi factor authentication</li>
</ul>
</li>
<li>secrets are versioned alongside the users that have access, i.e. even if a user is removed at 
some point, he can still decrypt a previous version of the encrypted secrets<ul>
<li>=&gt; must be mitigated by
<a class="post-section-overview" href="#reminder-rotate-the-encrypted-secrets">rotating the secrets themselves as well</a></li>
</ul>
</li>
</ul>

<p><a id="wrapping-up"> </a>
</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. You are now able to encrypt and decrypt secret files so that they can be stored  directly in the git repository.</p>
<p>In the next part of this tutorial, we will  <a target="_blank" href="https://www.pascallandau.com/blog/ci-pipeline-docker-php-gitlab-github/">set up a CI pipeline for dockerized PHP Apps on Github and Gitlab</a> that decrypts all necessary secrets and then runs our tests and qa tools.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)</p>
]]></content:encoded></item><item><title><![CDATA[Set up PHP QA tools and control them via make [Tutorial Part 5]]]></title><description><![CDATA[How to setup PHP QA tools in a dockerized application and control them via make This article appeared first on at Set up PHP QA tools and control them via…]]></description><link>https://pascallandau.hashnode.dev/set-up-php-qa-tools-and-control-them-via-make-tutorial-part-5</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/set-up-php-qa-tools-and-control-them-via-make-tutorial-part-5</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[PHP]]></category><category><![CDATA[QA]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Fri, 01 Jul 2022 05:08:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1656670710562/GEhPBq09A.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How to setup PHP QA tools in a dockerized application and control them via make</p>
<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/php-qa-tools-make-docker/">Set up PHP QA tools and control them via make [Tutorial Part 5]</a></p><p></p>
<hr />

<p>In the fifth part of this tutorial series on developing PHP on Docker we will <strong>setup some PHP code quality tools</strong> and provide a convenient way to control them via GNU make.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/php-qa-tools-make-docker/run-qa-tools.gif"><img src="https://www.pascallandau.com/img/php-qa-tools-make-docker/run-qa-tools.gif" alt="Run QA tools" /></a></p>
<p>
FYI: Originally I wanted this tutorial to be a part of 
<a href="https://www.pascallandau.com/blog/ci-pipeline-docker-php-gitlab-github/">Create a CI pipeline for dockerized PHP Apps</a>
because QA checks are imho vital part of a CI setup - but it kinda grew "too big" and took a way  too much space from, well, actually setting up the CI pipelines :)
</p>
<div class="youtube">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ocM4ktjqwIg"></iframe>
</div>

<p><strong>All code samples are publicly available</strong> in my <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.   You find the branch with the final result of this tutorial at <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-5-php-qa-tools-make-docker">part-5-php-qa-tools-make-docker</a>.</p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/run-laravel-9-docker-in-2022/">Run Laravel 9 on Docker in 2022</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/git-secret-encrypt-repository-docker/">Use git-secret to encrypt secrets in the repository</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>

<p><a id="table-of-contents"> </a>
</p>
<h2 id="heading-table-of-contents">Table of contents</h2>

<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a><ul>
<li><a class="post-section-overview" href="#the-qa-tools">The QA tools</a><ul>
<li><a class="post-section-overview" href="#phpcs-and-phpcbf">phpcs and phpcbf</a></li>
<li><a class="post-section-overview" href="#phpstan">phpstan</a></li>
<li><a class="post-section-overview" href="#php-parallel-lint">php-parallel-lint</a></li>
<li><a class="post-section-overview" href="#composer-require-checker">composer-require-checker</a></li>
<li><a class="post-section-overview" href="#additional-tools-out-of-scope">Additional tools (out of scope)</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#qa-make-targets">QA make targets</a><ul>
<li><a class="post-section-overview" href="#the-qa-target">The <code>qa</code> target</a></li>
<li><a class="post-section-overview" href="#the-execute-function">The <code>execute</code> "function"</a></li>
<li><a class="post-section-overview" href="#parallel-execution-and-a-helper-target">Parallel execution and a helper target</a></li>
<li><a class="post-section-overview" href="#sprinkle-some-color-on-top">Sprinkle some color on top</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#further-updates-in-the-codebase">Further updates in the codebase</a></li>
<li><a class="post-section-overview" href="#wrapping-up">Wrapping up</a></li>
</ul>
</li>
</ul>


<p><a id="introduction"> </a>
</p>
<h2 id="heading-introduction">Introduction</h2>
<p>Code quality tools ensure a <strong>baseline of code quality</strong> by automatically checking certain rules, e.g. <strong>code style definitions</strong>, proper <strong>usage of types</strong>, proper <strong>declaration of dependencies</strong>, etc. When run regularly they are a great way to enforce better code and are thus a
<strong>perfect fit for a CI pipeline</strong>. For this tutorial, I'm going to setup the following tools:</p>
<ul>
<li><a class="post-section-overview" href="#phpcs-and-phpcbf">Style Checker: phpcs</a><ul>
<li><a class="post-section-overview" href="#phpstan">Static Analyzer: phpstan</a></li>
<li><a class="post-section-overview" href="#php-parallel-lint">Code Linter: php-parallel-lint</a></li>
<li><a class="post-section-overview" href="#composer-require-checker">Dependency Checker: composer-require-checker</a></li>
</ul>
</li>
</ul>
<p>and provide convenient access through a <a class="post-section-overview" href="#the-qa-target"><code>qa</code> make target</a>. The end result will look like this:</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/php-qa-tools-make-docker/qa-tool-output.PNG"><img src="https://www.pascallandau.com/img/php-qa-tools-make-docker/qa-tool-output.PNG" alt="QA tool output" /></a></p>
<p>FYI: When we started out with using code quality tools in general, we have used  <a target="_blank" href="https://github.com/phpro/grumphp">GrumPHP</a> - and I would still recommend it. We have only  transitioned away from it because <code>make</code> gives us a little more flexibility and control.</p>
<p>You can find the "final" makefile at <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part-5-php-qa-tools-make-docker/.make/01-02-application-qa.mk"><code>.make/01-02-application-qa.mk</code></a>.</p>
<p><strong>CAUTION</strong>: The <code>Makefile</code> is build on top of the setup that I introduced in <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022</a>,  so please refer to that tutorial if anything is not clear.</p>
<pre><code class="lang-Makefile"><span class="hljs-comment">##@ [Application: QA]</span>

<span class="hljs-comment"># variables</span>
CORES?=<span class="hljs-variable">$(<span class="hljs-built_in">shell</span> (nproc  || sysctl -n hw.ncpu)</span> 2&gt; /dev/null)

<span class="hljs-comment"># constants</span>
 <span class="hljs-comment">## files</span>
ALL_FILES=./
APP_FILES=app/
TEST_FILES=tests/

 <span class="hljs-comment">## bash colors</span>
RED:=\033[0;31m
GREEN:=\033[0;32m
YELLOW:=\033[0;33m
NO_COLOR:=\033[0m

<span class="hljs-comment"># Tool CLI config</span>
PHPUNIT_CMD=php vendor/bin/phpunit
PHPUNIT_ARGS= -c phpunit.xml
PHPUNIT_FILES=
PHPSTAN_CMD=php vendor/bin/phpstan analyse
PHPSTAN_ARGS=--level=9
PHPSTAN_FILES=<span class="hljs-variable">$(APP_FILES)</span> <span class="hljs-variable">$(TEST_FILES)</span>
PHPCS_CMD=php vendor/bin/phpcs
PHPCS_ARGS=--parallel=<span class="hljs-variable">$(CORES)</span> --standard=psr12
PHPCS_FILES=<span class="hljs-variable">$(APP_FILES)</span>
PHPCBF_CMD=php vendor/bin/phpcbf
PHPCBF_ARGS=<span class="hljs-variable">$(PHPCS_ARGS)</span>
PHPCBF_FILES=<span class="hljs-variable">$(PHPCS_FILES)</span>
PARALLEL_LINT_CMD=php vendor/bin/parallel-lint
PARALLEL_LINT_ARGS=-j 4 --exclude vendor/ --exclude .docker --exclude .git
PARALLEL_LINT_FILES=<span class="hljs-variable">$(ALL_FILES)</span>
COMPOSER_REQUIRE_CHECKER_CMD=php vendor/bin/composer-require-checker
COMPOSER_REQUIRE_CHECKER_ARGS=--ignore-parse-errors

<span class="hljs-comment"># call with NO_PROGRESS=true to hide tool progress (makes sense when invoking multiple tools together)</span>
NO_PROGRESS?=false
<span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(NO_PROGRESS)</span>,true)
    PHPSTAN_ARGS+= --no-progress
    PARALLEL_LINT_ARGS+= --no-progress
<span class="hljs-keyword">else</span>
    PHPCS_ARGS+= -p
    PHPCBF_ARGS+= -p
<span class="hljs-keyword">endif</span>

<span class="hljs-comment"># Use NO_PROGRESS=false when running individual tools.</span>
<span class="hljs-comment"># On  NO_PROGRESS=true  the corresponding tool has no output on success</span>
<span class="hljs-comment">#                       apart from its runtime but it will still print </span>
<span class="hljs-comment">#                       any errors that occured. </span>
<span class="hljs-keyword">define</span> execute
    if [ <span class="hljs-string">"<span class="hljs-variable">$(NO_PROGRESS)</span>"</span> = <span class="hljs-string">"false"</span> ]; then \
        eval <span class="hljs-string">"<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1) $(2) $(3) $(4)"</span>; \
    <span class="hljs-keyword">else</span> \
        START=$<span class="hljs-variable">$(date +%s)</span>; \
        printf <span class="hljs-string">"%-35s"</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>; \
        if OUTPUT=$<span class="hljs-variable">$(<span class="hljs-built_in">eval</span> "<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1)</span> $(2) $(3) $(4)<span class="hljs-string">" 2&gt;&amp;1); then \
            printf "</span> <span class="hljs-variable">$(GREEN)</span>%-6s<span class="hljs-variable">$(NO_COLOR)</span><span class="hljs-string">" "</span>done<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took <span class="hljs-variable">$(YELLOW)</span>$${RUNTIME}s<span class="hljs-variable">$(NO_COLOR)\n</span><span class="hljs-string">"; \
        else \
            printf "</span> <span class="hljs-variable">$(RED)</span>%-6s<span class="hljs-variable">$(NO_COLOR)</span><span class="hljs-string">" "</span>fail<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took <span class="hljs-variable">$(YELLOW)</span>$${RUNTIME}s<span class="hljs-variable">$(NO_COLOR)\n</span><span class="hljs-string">"; \
            echo "</span>$$OUTPUT<span class="hljs-string">"; \
            printf "</span>\n<span class="hljs-string">"; \
            exit 1; \
        fi; \
    fi
endef

.PHONY: test
test: ## Run all tests
    @<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> <span class="hljs-variable">$(PHPUNIT_CMD)</span> <span class="hljs-variable">$(PHPUNIT_ARGS)</span> <span class="hljs-variable">$(ARGS)</span>

.PHONY: phplint
phplint: ## Run phplint on all files
    @$(call execute,<span class="hljs-variable">$(PARALLEL_LINT_CMD)</span>,<span class="hljs-variable">$(PARALLEL_LINT_ARGS)</span>,<span class="hljs-variable">$(PARALLEL_LINT_FILES)</span>, <span class="hljs-variable">$(ARGS)</span>)

.PHONY: phpcs
phpcs: ## Run style check on all application files
    @$(call execute,<span class="hljs-variable">$(PHPCS_CMD)</span>,<span class="hljs-variable">$(PHPCS_ARGS)</span>,<span class="hljs-variable">$(PHPCS_FILES)</span>, <span class="hljs-variable">$(ARGS)</span>)

.PHONY: phpcbf
phpcbf: ## Run style fixer on all application files
    @$(call execute,<span class="hljs-variable">$(PHPCBF_CMD)</span>,<span class="hljs-variable">$(PHPCBF_ARGS)</span>,<span class="hljs-variable">$(PHPCBF_FILES)</span>, <span class="hljs-variable">$(ARGS)</span>)

.PHONY: phpstan
phpstan:  ## Run static analyzer on all application and test files 
    @$(call execute,<span class="hljs-variable">$(PHPSTAN_CMD)</span>,<span class="hljs-variable">$(PHPSTAN_ARGS)</span>,<span class="hljs-variable">$(PHPSTAN_FILES)</span>, <span class="hljs-variable">$(ARGS)</span>)

.PHONY: composer-require-checker
composer-require-checker: ## Run dependency checker
    @$(call execute,<span class="hljs-variable">$(COMPOSER_REQUIRE_CHECKER_CMD)</span>,<span class="hljs-variable">$(COMPOSER_REQUIRE_CHECKER_ARGS)</span>,"</span><span class="hljs-string">", <span class="hljs-variable">$(ARGS)</span>)

.PHONY: qa
qa: ## Run code quality tools on all files
    @"</span><span class="hljs-variable">$(MAKE)</span><span class="hljs-string">" -j <span class="hljs-variable">$(CORES)</span> -k --no-print-directory --output-sync=target qa-exec NO_PROGRESS=true

.PHONY: qa-exec
qa-exec: phpstan \
    phplint \
    composer-require-checker \
    phpcs</span>
</code></pre>

<p><a id="the-qa-tools"> </a>
</p>
<h2 id="heading-the-qa-tools">The QA tools</h2>

<p><a id="phpcs-and-phpcbf"> </a>
</p>
<h3 id="heading-phpcs-and-phpcbf">phpcs and phpcbf</h3>
<p><code>phpcs</code> is the CLI tool of the style checker <a target="_blank" href="https://github.com/squizlabs/PHP_CodeSniffer">squizlabs/PHP_CodeSniffer</a>. It also comes with <code>phpcbf</code> - a tool to automatically fix style errors.</p>
<p>Installation via composer:</p>
<pre><code class="lang-shell">make composer ARGS="require --dev squizlabs/php_codesniffer"
</code></pre>
<p>For now we will simply use the pre-configured ruleset for <a target="_blank" href="https://www.php-fig.org/psr/psr-12/">PSR-12: Extended Coding Style</a>. When run in the <code>application</code> container for the first time on the <code>app</code> directory via</p>
<pre><code class="lang-text">vendor/bin/phpcs --standard=PSR12 --parallel=4 -p app
</code></pre>
<p>i.e.</p>
<pre><code class="lang-text">--standard=PSR12 =&gt; use the PSR12 ruleset
--parallel=4     =&gt; run with 4 parallel processes
-p               =&gt; show the progress
</code></pre>
<p>we get the following result:</p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/phpcs --standard=PSR12 --parallel=4 -p app

FILE: /var/www/app/app/Console/Kernel.php
----------------------------------------------------------------------
FOUND 2 ERRORS AFFECTING 1 LINE
----------------------------------------------------------------------
 28 | ERROR | [x] Expected at least 1 space before "."; 0 found
 28 | ERROR | [x] Expected at least 1 space after "."; 0 found
----------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------


FILE: /var/www/app/app/Http/Controllers/HomeController.php
----------------------------------------------------------------------
FOUND 4 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
 37 | ERROR | [x] Expected at least 1 space before "."; 0 found
 37 | ERROR | [x] Expected at least 1 space after "."; 0 found
 45 | ERROR | [x] Expected at least 1 space before "."; 0 found
 45 | ERROR | [x] Expected at least 1 space after "."; 0 found
----------------------------------------------------------------------
PHPCBF CAN FIX THE 4 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------


FILE: /var/www/app/app/Jobs/InsertInDbJob.php
-------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
-------------------------------------------------------------------------------
 13 | ERROR | [x] Each imported trait must have its own "use" import statement
-------------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-------------------------------------------------------------------------------


FILE: /var/www/app/app/Models/User.php
-------------------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
-------------------------------------------------------------------------------
 13 | ERROR | [x] Each imported trait must have its own "use" import statement
-------------------------------------------------------------------------------
PHPCBF CAN FIX THE 1 MARKED SNIFF VIOLATIONS AUTOMATICALLY
-------------------------------------------------------------------------------
</code></pre>
<p>All errors can be fixed automatically with <code>phpcbf</code>:</p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/phpcbf --standard=PSR12 --parallel=4 -p app

PHPCBF RESULT SUMMARY
-------------------------------------------------------------------------
FILE                                                     FIXED  REMAINING
-------------------------------------------------------------------------
/var/www/app/app/Console/Kernel.php                      2      0
/var/www/app/app/Http/Controllers/HomeController.php     4      0
/var/www/app/app/Jobs/InsertInDbJob.php                  1      0
/var/www/app/app/Models/User.php                         1      0
-------------------------------------------------------------------------
A TOTAL OF 8 ERRORS WERE FIXED IN 4 FILES
-------------------------------------------------------------------------

Time: 411ms; Memory: 8MB
</code></pre>
<p>and a follow-up run of <code>phpcs</code> doesn't show any more errors:</p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/phpcs --standard=PSR12 --parallel=4 -p app
.................... 20 / 20 (100%)


Time: 289ms; Memory: 8MB
</code></pre>

<p><a id="phpstan"> </a>
</p>
<h3 id="heading-phpstan">phpstan</h3>
<p><code>phpstan</code> is the CLI tool of the static code analyzer <a target="_blank" href="https://github.com/phpstan/phpstan">phpstan/phpstan</a> (see also the <a target="_blank" href="https://phpstan.org/user-guide/getting-started">full PHPStan documentation</a>). It provides some default "levels" of increasing strictness to report potential bugs based on the AST of the analyzed PHP code.</p>
<p>Installation via composer:</p>
<pre><code class="lang-shell">make composer ARGS="require --dev phpstan/phpstan"
</code></pre>
<p>Since this is a "fresh" codebase with very little code let's go for the <a target="_blank" href="https://phpstan.org/user-guide/rule-levels">highest level 9</a> (as of 2022-04-24) and run it in the <code>application</code> container on the <code>app</code> and <code>tests</code> directories via:</p>
<pre><code class="lang-text">vendor/bin/phpstan analyse app tests --level=9

--level=9        =&gt; use level 9
</code></pre>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/phpstan analyse app tests --level=9
 25/25 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ------------------------------------------------------------------------------------------------------------------
  Line   app/Commands/SetupDbCommand.php
 ------ ------------------------------------------------------------------------------------------------------------------
  22     Method App\Commands\SetupDbCommand::getOptions() return type has no value type specified in iterable type array.
         � See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type
  34     Method App\Commands\SetupDbCommand::handle() has no return type specified.
 ------ ------------------------------------------------------------------------------------------------------------------

 ------ -------------------------------------------------------------------------------------------------------
  Line   app/Http/Controllers/HomeController.php
 ------ -------------------------------------------------------------------------------------------------------
  22     Parameter #1 $jobId of class App\Jobs\InsertInDbJob constructor expects string, mixed given.
  25     Part $jobId (mixed) of encapsed string cannot be cast to string.
  35     Call to an undefined method Illuminate\Redis\Connections\Connection::lRange().
  62     Call to an undefined method Illuminate\Contracts\View\Factory|Illuminate\Contracts\View\View::with().
 ------ -------------------------------------------------------------------------------------------------------

 ------ ------------------------------------------------------------------------------------------------------------------
  Line   app/Http/Middleware/Authenticate.php
 ------ ------------------------------------------------------------------------------------------------------------------
  17     Method App\Http\Middleware\Authenticate::redirectTo() should return string|null but return statement is missing.
 ------ ------------------------------------------------------------------------------------------------------------------

 ------ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Line   app/Http/Middleware/RedirectIfAuthenticated.php
 ------ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  26     Method App\Http\Middleware\RedirectIfAuthenticated::handle() should return Illuminate\Http\RedirectResponse|Illuminate\Http\Response but returns Illuminate\Http\RedirectResponse|Illuminate\Routing\Redirector.
 ------ ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 ------ -----------------------------------------------------------------------
  Line   app/Jobs/InsertInDbJob.php
 ------ -----------------------------------------------------------------------
  22     Method App\Jobs\InsertInDbJob::handle() has no return type specified.
 ------ -----------------------------------------------------------------------

 ------ -------------------------------------------------
  Line   app/Providers/RouteServiceProvider.php
 ------ -------------------------------------------------
  36     PHPDoc tag @var above a method has no effect.
  36     PHPDoc tag @var does not specify variable name.
  60     Cannot access property $id on mixed.
 ------ -------------------------------------------------

 ------ ----------------------------------------------------------------------------------------------------------------------------------------------------------
  Line   tests/Feature/App/Http/Controllers/HomeControllerTest.php
 ------ ----------------------------------------------------------------------------------------------------------------------------------------------------------
  24     Method Tests\Feature\App\Http\Controllers\HomeControllerTest::test___invoke() has parameter $params with no value type specified in iterable type array.
         � See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type
  38     Method Tests\Feature\App\Http\Controllers\HomeControllerTest::__invoke_dataProvider() return type has no value type specified in iterable type array.
         � See: https://phpstan.org/blog/solving-phpstan-no-value-type-specified-in-iterable-type
 ------ ----------------------------------------------------------------------------------------------------------------------------------------------------------

 ------ ---------------------------------------------------------------------------------------------------------------------
  Line   tests/TestCase.php
 ------ ---------------------------------------------------------------------------------------------------------------------
  68     Cannot access offset 'database' on mixed.
  71     Parameter #1 $config of method Illuminate\Database\Connectors\MySqlConnector::connect() expects array, mixed given.
 ------ ---------------------------------------------------------------------------------------------------------------------


 [ERROR] Found 16 errors
</code></pre>
<p>After fixing (or ignoring :P) all errors, we now get</p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/phpstan analyse app tests --level=9
25/25 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

[OK] No errors
</code></pre>

<p><a id="php-parallel-lint"> </a>
</p>
<h3 id="heading-php-parallel-lint">php-parallel-lint</h3>
<p><code>php-parallel-lint</code> is the CLI tool of the PHP code linter <a target="_blank" href="https://github.com/php-parallel-lint/PHP-Parallel-Lint">php-parallel-lint/PHP-Parallel-Lint</a>. It ensures that all PHP files are syntactically correct.</p>
<p>Installation via composer:</p>
<pre><code class="lang-shell">make composer ARGS="require --dev php-parallel-lint/php-parallel-lint"
</code></pre>
<p>"Parallel" is already in the name, so we run it on the full codebase <code>./</code> with 4 parallel processes  and exclude the <code>.git</code> and <code>vendor</code> directories to speed up the execution via</p>
<pre><code class="lang-text">vendor/bin/parallel-lint -j 4 --exclude .git --exclude vendor ./
</code></pre>
<p>i.e.</p>
<pre><code class="lang-text">-j 4                              =&gt; use 4 parallel processes
--exclude .git --exclude vendor   =&gt; ignore the .git/ and vendor/ directories
</code></pre>
<p>we get </p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/parallel-lint -j 4 --exclude .git --exclude vendor ./
PHP 8.1.1 | 4 parallel jobs
............................................................ 60/61 (98 %)
.                                                            61/61 (100 %)


Checked 61 files in 0.2 seconds
No syntax error found
</code></pre>
<p>No further TODOs here.</p>

<p><a id="composer-require-checker"> </a>
</p>
<h3 id="heading-composer-require-checker">composer-require-checker</h3>
<p><code>composer-require-checker</code> is the CLI tool of the dependency checker <a target="_blank" href="https://github.com/maglnet/ComposerRequireChecker">maglnet/ComposerRequireChecker</a>. The tool ensures that the <code>composer.json</code> file contains all dependencies that are used in the codebase.</p>
<p>Installation via composer:</p>
<pre><code class="lang-shell">make composer ARGS="require --dev maglnet/composer-require-checker"
</code></pre>
<p>Run it via</p>
<pre><code class="lang-text">vendor/bin/composer-require-checker check
</code></pre>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/composer-require-checker check
ComposerRequireChecker 4.0.0@baa11a4e9e5072117e3d180ef16c07036cafa4a2
The following 1 unknown symbols were found:
+---------------------------------------------+--------------------+
| Unknown Symbol                              | Guessed Dependency |
+---------------------------------------------+--------------------+
| Symfony\Component\Console\Input\InputOption |                    |
+---------------------------------------------+--------------------+
</code></pre>
<p>What's going on here?</p>
<p>We use <code>Symfony\Component\Console\Input\InputOption</code> in our <code>\App\Commands\SetupDbCommand</code> and the code doesn't "fail" because <code>InputOption</code> is defined in the<code>symfony/console</code> package that is a
<strong>transitive dependency</strong> of <code>laravel/framework</code>, see the <a target="_blank" href="https://github.com/laravel/framework/blob/5b113dad7d2c88e15b65d987ca63f03b2be43e6a/composer.json#L34"><code>laravel/framework composer.json</code></a> file. </p>
<p>I.e. the <code>symfony/console</code> package <strong>does actually exist</strong> in our <code>vendor</code> directory - but since we also use it <em>as a first-party-dependency directly in our code</em>, we must declare the dependency explicitly. Otherwise, Laravel might at some point decide to drop <code>symfony/console</code> and we would be left with broken code.</p>
<p>To fix this, I run</p>
<pre><code class="lang-shell">make composer ARGS="require symfony/console"
</code></pre>
<p>which will update the <code>composer.json</code> file and add the dependency. Running <code>composer-require-checker</code> again will now yield no further errors.</p>
<pre><code class="lang-text">root:/var/www/app# vendor/bin/composer-require-checker check
ComposerRequireChecker 4.0.0@baa11a4e9e5072117e3d180ef16c07036cafa4a2
There were no unknown symbols found.
</code></pre>

<p><a id="additional-tools-out-of-scope"> </a>
</p>
<h3 id="heading-additional-tools-out-of-scope">Additional tools (out of scope)</h3>
<p>In general, I'm a huge fan of code quality tools and we use them quite extensively. At some  point I'll probably dedicate a whole article to go over them in detail - but for now I'm just  gonna leave a list for inspiration:</p>
<ul>
<li><a target="_blank" href="https://packagist.org/packages/brianium/paratest">brianium/paratest</a><ul>
<li>Running PhpUnit tests in parallel</li>
<li><a target="_blank" href="https://packagist.org/packages/malukenho/mcbumpface">malukenho/mcbumpface</a><ul>
<li>Update the versions in the <code>composer.json</code> file after an update</li>
</ul>
</li>
<li><a target="_blank" href="https://packagist.org/packages/qossmic/deptrac-shim">qossmic/deptrac-shim</a><ul>
<li>A shim for <a target="_blank" href="https://packagist.org/packages/qossmic/deptrac">qossmic/deptrac</a>: 
A tool to define dependency layers based on e.g. namespaces</li>
</ul>
</li>
<li><a target="_blank" href="https://packagist.org/packages/icanhazstring/composer-unused">icanhazstring/composer-unused</a><ul>
<li>Show dependencies in the <code>composer.json</code> that are not used in the codebase</li>
</ul>
</li>
<li><a target="_blank" href="https://packagist.org/packages/roave/security-advisories">roave/security-advisories</a><ul>
<li>Gives a warning when packages with known vulnerabilities are used </li>
<li>Alternative: <a target="_blank" href="https://github.com/fabpot/local-php-security-checker/">local-php-security-checker</a></li>
</ul>
</li>
</ul>
</li>
</ul>

<p><a id="qa-make-targets"> </a>
</p>
<h2 id="heading-qa-make-targets">QA make targets</h2>
<p>You might have noticed that <strong>all tools have their own configuration options</strong>. Instead of remembering each of them, I'll define corresponding make targets in <code>.make/01-02-application-qa.mk</code>. The easiest way to do so would be to "hard-code" the exact commands that I ran previously, e.g.</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: phpstan</span>
<span class="hljs-section">phpstan:  ## Run static analyzer on all application and test files </span>
    @<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> vendor/bin/phpstan analyse app tests --level=9
</code></pre>
<p>(Please refer to the <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/#run-commands-in-the-docker-containers">Run commands in the docker containers</a> section in the previous tutorial for an explanation of the <code>EXECUTE_IN_APPLICATION_CONTAINER</code>  variable).</p>
<p>However, this implementation is quite inflexible: What if we want to check a single file or try out other options? So let's create some variables instead:</p>
<pre><code class="lang-makefile">PHPSTAN_CMD=php vendor/bin/phpstan analyse
PHPSTAN_ARGS=--level=9
PHPSTAN_FILES=<span class="hljs-variable">$(APP_FILES)</span> <span class="hljs-variable">$(TEST_FILES)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: phpstan</span>
<span class="hljs-section">phpstan: ## Run static analyzer on all application and test files </span>
    @<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> <span class="hljs-variable">$(PHPSTAN_CMD)</span> <span class="hljs-variable">$(PHPSTAN_ARGS)</span> <span class="hljs-variable">$(PHPSTAN_FILES)</span>
</code></pre>
<p>This target allows me to override the defaults and e.g. check only the file  <code>app/Commands/SetupDbCommand.php</code> with <code>--level=1</code></p>
<pre><code class="lang-shell">make phpstan PHPSTAN_FILES=app/Commands/SetupDbCommand.php PHPSTAN_ARGS="--level=1"
</code></pre>
<pre><code class="lang-text">$ make phpstan PHPSTAN_FILES=app/Commands/SetupDbCommand.php PHPSTAN_ARGS="--level=1" 
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%


 [OK] No errors
</code></pre>
<p>The remaining tool variables can be configured in the exact same way:</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># constants</span>
 <span class="hljs-comment">## files</span>
ALL_FILES=./
APP_FILES=app/
TEST_FILES=tests/

<span class="hljs-comment"># Tool CLI config</span>
PHPUNIT_CMD=php vendor/bin/phpunit
PHPUNIT_ARGS= -c phpunit.xml
PHPUNIT_FILES=
PHPSTAN_CMD=php vendor/bin/phpstan analyse
PHPSTAN_ARGS=--level=9
PHPSTAN_FILES=<span class="hljs-variable">$(APP_FILES)</span> <span class="hljs-variable">$(TEST_FILES)</span>
PHPCS_CMD=php vendor/bin/phpcs
PHPCS_ARGS=--parallel=<span class="hljs-variable">$(CORES)</span> --standard=psr12
PHPCS_FILES=<span class="hljs-variable">$(APP_FILES)</span>
PHPCBF_CMD=php vendor/bin/phpcbf
PHPCBF_ARGS=<span class="hljs-variable">$(PHPCS_ARGS)</span>
PHPCBF_FILES=<span class="hljs-variable">$(PHPCS_FILES)</span>
PARALLEL_LINT_CMD=php vendor/bin/parallel-lint
PARALLEL_LINT_ARGS=-j 4 --exclude vendor/ --exclude .docker --exclude .git
PARALLEL_LINT_FILES=<span class="hljs-variable">$(ALL_FILES)</span>
COMPOSER_REQUIRE_CHECKER_CMD=php vendor/bin/composer-require-checker
COMPOSER_REQUIRE_CHECKER_ARGS=--ignore-parse-errors
</code></pre>

<p><a id="the-qa-target"> </a>
</p>
<h3 id="heading-the-qa-target">The <code>qa</code> target</h3>
<p>From a workflow perspective I usually want to <strong>run all configured qa tools</strong> instead of each one individually (being able to run individually is still great if a tool fails, though).</p>
<p>A trivial approach would be a new target that <strong>uses all individual tool targets as preconditions</strong>:</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: qa</span>
<span class="hljs-section">qa: phpstan \</span>
    phplint \
    composer-require-checker \
    phpcs
</code></pre>
<p>But we can do better, because this target produces quite a noisy output:</p>
<pre><code class="lang-text">$ make qa
 25/25 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%


 [OK] No errors

PHP 8.1.1 | 4 parallel jobs
............................................................ 60/61 (98 %)
.                                                            61/61 (100 %)


Checked 61 files in 0.3 seconds
No syntax error found
ComposerRequireChecker 4.0.0@baa11a4e9e5072117e3d180ef16c07036cafa4a2
There were no unknown symbols found.
.................... 20 / 20 (100%)


Time: 576ms; Memory: 8MB
</code></pre>
<p>I'd rather have something like this:</p>
<pre><code class="lang-text">$ make qa
phplint                             done   took 1s
phpcs                               done   took 1s
phpstan                             done   took 3s
composer-require-checker            done   took 6s
</code></pre>

<p><a id="the-execute-function"> </a>
</p>
<h3 id="heading-the-execute-function">The <code>execute</code> "function"</h3>
<p>We'll make this work by <strong>suppressing the tool output</strong> and <strong>using a user-defined <code>execute</code> make function</strong> to format all targets nicely. </p>
<p>Though "function" isn't quite correct here, because it's rather a <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Multi_002dLine.html#Multi_002dLine">multiline variable</a> defined via <code>define ... endef</code> that is then "invoked" via the <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Call-Function.html">call function</a>.
</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># File: 01-02-application-qa.mk</span>

<span class="hljs-comment"># call with NO_PROGRESS=true to hide tool progress (makes sense when invoking multiple tools together)</span>
NO_PROGRESS?=false
<span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(NO_PROGRESS)</span>,true)
    PHPSTAN_ARGS+= --no-progress
<span class="hljs-keyword">endif</span>


<span class="hljs-comment"># Use NO_PROGRESS=false when running individual tools.</span>
<span class="hljs-comment"># On  NO_PROGRESS=true  the corresponding tool has no output on success</span>
<span class="hljs-comment">#                       apart from its runtime but it will still print </span>
<span class="hljs-comment">#                       any errors that occured. </span>
<span class="hljs-keyword">define</span> execute
    if [ <span class="hljs-string">"<span class="hljs-variable">$(NO_PROGRESS)</span>"</span> = <span class="hljs-string">"false"</span> ]; then \
        eval <span class="hljs-string">"<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1) $(2) $(3) $(4)"</span>; \
    <span class="hljs-keyword">else</span> \
        START=$<span class="hljs-variable">$(date +%s)</span>; \
        printf <span class="hljs-string">"%-35s"</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>; \
        if OUTPUT=$<span class="hljs-variable">$(<span class="hljs-built_in">eval</span> "<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1)</span> $(2) $(3) $(4)<span class="hljs-string">" 2&gt;&amp;1); then \
            printf "</span> %-6s<span class="hljs-string">" "</span>done<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took $${RUNTIME}s\n<span class="hljs-string">"; \
        else \
            printf "</span> %-6s<span class="hljs-string">" "</span>fail<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took $${RUNTIME}s\n<span class="hljs-string">"; \
            echo "</span>$$OUTPUT<span class="hljs-string">"; \
            printf "</span>\n<span class="hljs-string">"; \
            exit 1; \
        fi; \
    fi
endef</span>
</code></pre>
<ul>
<li>the <code>NO_PROGRESS</code> variable is set to <code>false</code> by default and will cause a target to be invoked
as before, showing all its output immediately<ul>
<li>if the variable is set to <code>true</code>, the target is instead invoked via <code>eval</code> and the output is
captured in the <code>OUTPUT</code> bash variable that will only be printed if the result of the
invocation is faulty</li>
</ul>
</li>
</ul>
<p>The tool targets are then adjusted to use the new function.</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: phpstan</span>
<span class="hljs-section">phpstan: ## Run static analyzer on all application and test files</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">call</span> execute,<span class="hljs-variable">$(PHPSTAN_CMD)</span>,<span class="hljs-variable">$(PHPSTAN_ARGS)</span>,<span class="hljs-variable">$(PHPSTAN_FILES)</span>,<span class="hljs-variable">$(ARGS)</span>)</span>
</code></pre>
<p>We can now call the <code>phpstan</code> target with <code>NO_PROGRESS=true</code> like so:</p>
<pre><code class="lang-text">$ make phpstan NO_PROGRESS=true
phpstan                             done   took 4s
</code></pre>
<p>An "error" would look likes this:</p>
<pre><code class="lang-text">$ make phpstan NO_PROGRESS=true
phpstan                             fail   took 9s
 ------ ----------------------------------------
  Line   app/Providers/RouteServiceProvider.php
 ------ ----------------------------------------
  49     Cannot access property $id on mixed.
 ------ ----------------------------------------
</code></pre>

<p><a id="parallel-execution-and-a-helper-target"> </a>
</p>
<h3 id="heading-parallel-execution-and-a-helper-target">Parallel execution and a helper target</h3>
<p>Technically, this also already works with the <code>qa</code> target and we can even speed up the process by 
<strong>running the tools in parallel</strong> with the <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Parallel.html">-j flag for "Parallel Execution"</a></p>
<pre><code class="lang-text">$ make -j 4 qa NO_PROGRESS=true
phpstan                            phplint                            composer-require-checker           phpcs                               done   took 5s
done   took 5s
done   took 7s
done   took 10s
</code></pre>
<p>Well... not quite what we wanted. We also need to use  <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Parallel-Output.html"><code>--output-sync=target</code> to controll the "Output During Parallel Execution"</a></p>
<pre><code class="lang-text">$ make -j 4 --output-sync=target qa NO_PROGRESS=true
phpstan                             done   took 3s
phplint                             done   took 1s
composer-require-checker            done   took 5s
phpcs                               done   took 1s
</code></pre>
<p>Since this is quite a mouthful to type, we'll use a helper target <code>qa-exec</code> for running the tools and put all the inconvenient-to-type options in the final <code>qa</code> target.</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># File: 01-02-application-qa.mk</span>
<span class="hljs-comment">#...</span>

<span class="hljs-comment"># variables</span>
CORES?=<span class="hljs-variable">$(<span class="hljs-built_in">shell</span> (nproc  || sysctl -n hw.ncpu)</span> 2&gt; /dev/null)

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: qa</span>
<span class="hljs-section">qa: ## Run code quality tools on all files</span>
    @<span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> -j <span class="hljs-variable">$(CORES)</span> -k --no-print-directory --output-sync=target qa-exec NO_PROGRESS=true

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: qa-exec</span>
<span class="hljs-section">qa-exec: phpstan \</span>
    phplint \
    composer-require-checker \
    phpcs
</code></pre>
<p>For the number of parallel processes I use <code>nproc</code> (works on Linux and Windows) resp.  <code>sysctl -n hw.ncpu</code> (works on Mac) to determine the number of available cores. If you dedicate  less resources to docker you might want to hard-code this setting to a lower value (e.g. by  adding a <code>CORES</code> variable in  the <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/#shared-variables-make-env"><code>.make/.env</code></a>  file).</p>

<p><a id="sprinkle-some-color-on-top"> </a>
</p>
<h3 id="heading-sprinkle-some-color-on-top">Sprinkle some color on top</h3>
<p>The final piece for getting to the output mentioned in the <a class="post-section-overview" href="#introduction">Introduction</a> is the  bash-coloring:</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/php-qa-tools-make-docker/qa-tool-output.PNG"><img src="https://www.pascallandau.com/img/php-qa-tools-make-docker/qa-tool-output.PNG" alt="QA tool output" /></a></p>
<p>To make this work, we need to understand first how colors work in bash:</p>
<blockquote>
<p>This  [coloring] can be accomplished by adding a <code>\e</code> [or <code>\033</code>] at the beginning to form an 
escape sequence. The escape sequence for specifying color codes is <code>\e[COLORm</code>
(<code>COLOR</code> represents our (numeric) color code in this case).</p>
</blockquote>
<p>(via <a target="_blank" href="https://dev.to/ifenna__/adding-colors-to-bash-scripts-48g4">Adding colors to Bash scripts</a>)</p>
<p>E.g. the following script will print a green text:</p>
<pre><code class="lang-shell">printf "\033[0;32mThis text is green\033[0m"
</code></pre>
<p>So we define the required colors as variables and use them in the corresponding places in the <a class="post-section-overview" href="#the-execute-function"><code>execute</code> function</a>:</p>
<pre><code class="lang-makefile"> <span class="hljs-comment">## bash colors</span>
RED:=\033[0;31m
GREEN:=\033[0;32m
YELLOW:=\033[0;33m
NO_COLOR:=\033[0m

<span class="hljs-comment"># ...</span>

<span class="hljs-comment"># Use NO_PROGRESS=false when running individual tools.</span>
<span class="hljs-comment"># On  NO_PROGRESS=true  the corresponding tool has no output on success</span>
<span class="hljs-comment">#                       apart from its runtime but it will still print </span>
<span class="hljs-comment">#                       any errors that occured. </span>
<span class="hljs-keyword">define</span> execute
    if [ <span class="hljs-string">"<span class="hljs-variable">$(NO_PROGRESS)</span>"</span> = <span class="hljs-string">"false"</span> ]; then \
        eval <span class="hljs-string">"<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1) $(2) $(3) $(4)"</span>; \
    <span class="hljs-keyword">else</span> \
        START=$<span class="hljs-variable">$(date +%s)</span>; \
        printf <span class="hljs-string">"%-35s"</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>; \
        if OUTPUT=$<span class="hljs-variable">$(<span class="hljs-built_in">eval</span> "<span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> $(1)</span> $(2) $(3) $(4)<span class="hljs-string">" 2&gt;&amp;1); then \
            printf "</span> <span class="hljs-variable">$(GREEN)</span>%-6s<span class="hljs-variable">$(NO_COLOR)</span><span class="hljs-string">" "</span>done<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took <span class="hljs-variable">$(YELLOW)</span>$${RUNTIME}s<span class="hljs-variable">$(NO_COLOR)\n</span><span class="hljs-string">"; \
        else \
            printf "</span> <span class="hljs-variable">$(RED)</span>%-6s<span class="hljs-variable">$(NO_COLOR)</span><span class="hljs-string">" "</span>fail<span class="hljs-string">"; \
            END=$$(date +%s); \
            RUNTIME=$$((END-START)) ;\
            printf "</span> took <span class="hljs-variable">$(YELLOW)</span>$${RUNTIME}s<span class="hljs-variable">$(NO_COLOR)\n</span><span class="hljs-string">"; \
            echo "</span>$$OUTPUT<span class="hljs-string">"; \
            printf "</span>\n<span class="hljs-string">"; \
            exit 1; \
        fi; \
    fi
endef</span>
</code></pre>
<p>Please note, that i did <strong>not include the tests in the <code>qa</code> target</strong>. I like to run those  separately, because our tests usually take a lot longer to execute. So in my day-to-day work I  would run <code>make qa</code> and <code>make test</code> to ensure that code quality and tests are passing:</p>
<pre><code class="lang-text">$ make qa
phplint                             done   took 1s
phpcs                               done   took 1s
composer-require-checker            done   took 14s
phpstan                             done   took 16s

$ make test
PHPUnit 9.5.19 #StandWithUkraine

.......                                                             7 / 7 (100%)

Time: 00:03.772, Memory: 28.00 MB

OK (7 tests, 13 assertions)
</code></pre>

<p><a id="further-updates-in-the-codebase"> </a>
</p>
<h2 id="heading-further-updates-in-the-codebase">Further updates in the codebase</h2>
<p>I've also cleaned up the codebase a little in branch  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-5-php-qa-tools-make-docker">part-5-php-qa-tools-make-docker</a> and even though those changes have nothing to todo with "QA tools" I didn't want to leave them  unnoticed:</p>
<ul>
<li><p>removing unnecessary files (<code>.styleci.yml</code>, <code>package.json</code>, <code>webpack.mix.js</code>)</p>
<ul>
<li>removing unused values from the <code>.env.example</code> file</li>
<li>run a <code>composer update</code> to get the latest Laravel version</li>
<li><p>add a <code>show-help</code> script to the <code>scripts</code> section of the <code>composer.json</code> file that references the 
<code>Makefile</code> (see also <a target="_blank" href="https://twitter.com/PascalLandau/status/1518227256648343552">this discussion on Twitter</a>)</p>
<pre><code class="lang-json">
{
    <span class="hljs-attr">"scripts"</span>: {
        <span class="hljs-attr">"show-help"</span>: [
            <span class="hljs-string">"make"</span>
        ]
    },
    <span class="hljs-attr">"scripts-descriptions"</span>: {
        <span class="hljs-attr">"show-help"</span>: <span class="hljs-string">"Display available 'make' commands (we use make instead of composer scripts)."</span>
    }
}
</code></pre>
<p><a target="_blank" href="https://www.pascallandau.com/img/php-qa-tools-make-docker/make-composer-scripts.gif"><img src="https://www.pascallandau.com/img/php-qa-tools-make-docker/make-composer-scripts.gif" alt="Run make via composer script" /></a></p>
</li>
<li>replace <code>docker-compose</code> with <code>docker compose</code> to use <a target="_blank" href="https://docs.docker.com/compose/cli-command/">compose v2</a></li>
</ul>
</li>
</ul>
<p>For some reason, the last point caused some trouble because Linux and Docker Desktop for Windows  require a <code>-T</code> flag for the <code>exec</code> command to disable a TTY allocation in some cases. Whereas on  Docker Desktop for Mac  <a target="_blank" href="https://github.com/moby/moby/issues/37366#issuecomment-527099456">the missing TTY lead to a cluttered output ("staircase effect")</a>.</p>
<p>Thus I modified the <code>Makefile</code> to populate a <code>DOCKER_COMPOSE_EXEC_OPTIONS</code> variable based on the OS</p>
<pre><code class="lang-makefile"><span class="hljs-comment"># Add the -T options to "docker compose exec" to avoid the </span>
<span class="hljs-comment"># "panic: the handle is invalid"</span>
<span class="hljs-comment"># error on Windows and Linux </span>
<span class="hljs-comment"># @see https://stackoverflow.com/a/70856332/413531</span>
DOCKER_COMPOSE_EXEC_OPTIONS=-T

<span class="hljs-comment"># OS is defined for WIN systems, so "uname" will not be executed</span>
OS?=<span class="hljs-variable">$(<span class="hljs-built_in">shell</span> uname)</span>
<span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(OS)</span>,Windows_NT)
    <span class="hljs-comment"># Windows requires the .exe extension, otherwise the entry is ignored</span>
    <span class="hljs-comment"># @see https://stackoverflow.com/a/60318554/413531</span>
    SHELL := bash.exe
<span class="hljs-keyword">else</span> <span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(OS)</span>,Darwin)
    <span class="hljs-comment"># On Mac, the -T must be omitted to avoid cluttered output</span>
    <span class="hljs-comment"># @see https://github.com/moby/moby/issues/37366#issuecomment-401157643</span>
    DOCKER_COMPOSE_EXEC_OPTIONS=
<span class="hljs-keyword">endif</span>
</code></pre>
<p>And use the variable when defining <code>EXECUTE_IN_*_CONTAINER</code> in <code>.make/02-00-docker.mk</code></p>
<pre><code class="lang-makefile"><span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(EXECUTE_IN_CONTAINER)</span>,true)
    EXECUTE_IN_ANY_CONTAINER:=<span class="hljs-variable">$(DOCKER_COMPOSE)</span> exec <span class="hljs-variable">$(DOCKER_COMPOSE_EXEC_OPTIONS)</span> --user <span class="hljs-variable">$(APP_USER_NAME)</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span>
    EXECUTE_IN_APPLICATION_CONTAINER:=<span class="hljs-variable">$(DOCKER_COMPOSE)</span> exec <span class="hljs-variable">$(DOCKER_COMPOSE_EXEC_OPTIONS)</span> --user <span class="hljs-variable">$(APP_USER_NAME)</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME_APPLICATION)</span>
    EXECUTE_IN_WORKER_CONTAINER:=<span class="hljs-variable">$(DOCKER_COMPOSE)</span> exec <span class="hljs-variable">$(DOCKER_COMPOSE_EXEC_OPTIONS)</span> --user <span class="hljs-variable">$(APP_USER_NAME)</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME_PHP_WORKER)</span>
<span class="hljs-keyword">endif</span>
</code></pre>

<p><a id="wrapping-up"> </a>
</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. You should now have a blueprint for adding code quality tools for your dockerized application and way to conveniently control them through a Makefile.</p>
<p>In the next part of this tutorial, we will  <a target="_blank" href="https://www.pascallandau.com/blog/git-secret-encrypt-repository-docker/">set up git secret to encrypt secret values and store them directly in the git repository</a>.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)</p>
<p>;</p>
]]></content:encoded></item><item><title><![CDATA[Run Laravel 9 on Docker in 2022 [Tutorial Part 4]]]></title><description><![CDATA[How to set up Laravel with Artisan Commands, Controllers, a Queue + workers and a Database on Docker This article appeared first on at Run Laravel 9 on…]]></description><link>https://pascallandau.hashnode.dev/run-laravel-9-on-docker-in-2022-tutorial-part-4</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/run-laravel-9-on-docker-in-2022-tutorial-part-4</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Tue, 28 Jun 2022 07:38:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1656401951311/JKN3vIdJI.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How to set up Laravel with Artisan Commands, Controllers, a Queue + workers and a Database on Docker</p>
<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/run-laravel-9-docker-in-2022/">Run Laravel 9 on Docker in 2022 [Tutorial Part 4]</a></p><p></p>
<hr />

<p>In this part of my tutorial series on developing PHP on Docker we will install <strong>Laravel and make sure our setup works for Artisan Commands, a Redis Queue and Controllers</strong>
for the front end requests.</p>
<div class="youtube">
<iframe width="560" height="315" src="https://www.youtube.com/embed/BpsBzpMD87c"></iframe>
</div>

<p><strong>All code samples are publicly available</strong> in my <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.   You find the branch for this tutorial at <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-4-3-run-laravel-9-docker-in-2022">part-4-3-run-laravel-9-docker-in-2022</a>.</p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/phpstorm-docker-xdebug-3-php-8-1-in-2022/">PhpStorm, Docker and Xdebug 3 on PHP 8.1 in 2022</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/php-qa-tools-make-docker/">Set up PHP QA tools and control them via make</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>

<p><a id="table-of-contents"> </a>
</p>
<h2 id="heading-table-of-contents">Table of contents</h2>

<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#install-extensions">Install extensions</a></li>
<li><a class="post-section-overview" href="#install-laravel">Install Laravel</a></li>
<li><a class="post-section-overview" href="#update-the-php-poc">Update the PHP POC</a><ul>
<li><a class="post-section-overview" href="#config">config</a><ul>
<li><a class="post-section-overview" href="#database-connection">database connection</a></li>
<li><a class="post-section-overview" href="#queue-connection">queue connection</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#controllers">Controllers</a></li>
<li><a class="post-section-overview" href="#commands">Commands</a></li>
<li><a class="post-section-overview" href="#jobs-and-workers">Jobs and workers</a></li>
<li><a class="post-section-overview" href="#tests">Tests</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#makefile-updates">Makefile updates</a><ul>
<li><a class="post-section-overview" href="#clearing-the-queue">Clearing the queue</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#running-the-poc">Running the POC</a></li>
<li><a class="post-section-overview" href="#wrapping-up">Wrapping up</a></li>
</ul>


<p><a id="introduction"> </a>
</p>
<h2 id="heading-introduction">Introduction</h2>
<p>The goal of this tutorial is to run the  <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/#php-poc">PHP POC from part 4.1</a> using Laravel as a framework instead of "plain PHP".  We'll use the newest version of Laravel (Laravel 9) that was <a target="_blank" href="https://laravel-news.com/laravel-9-released">released at the beginning of February 2022</a>.</p>

<p><a id="install-extensions"> </a>
</p>
<h2 id="heading-install-extensions">Install extensions</h2>
<p>Before Laravel can be installed, we need to add the necessary extensions of the framework (and all its dependencies) to the <code>php-base</code> image:</p>
<pre><code><span class="hljs-comment"># File: .docker/images/php/base/Dockerfile</span>

<span class="hljs-comment"># ...</span>

<span class="hljs-attribute">RUN</span> apk add --update --<span class="hljs-literal">no</span>-cache  \
        php-curl~=<span class="hljs-variable">${TARGET_PHP_VERSION}</span> \
</code></pre>
<p><a id="install-laravel"> </a>
</p>
<h2 id="heading-install-laravel">Install Laravel</h2>
<p>We'll start by <a target="_blank" href="https://laravel.com/docs/9.x/installation#installation-via-composer">creating a new Laravel project with composer</a></p>
<pre><code>composer create<span class="hljs-operator">-</span>project <span class="hljs-operator">-</span><span class="hljs-operator">-</span>prefer<span class="hljs-operator">-</span>dist laravel<span class="hljs-operator">/</span>laravel <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>laravel <span class="hljs-string">"9.*"</span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>no<span class="hljs-operator">-</span>install <span class="hljs-operator">-</span><span class="hljs-operator">-</span>no<span class="hljs-operator">-</span>scripts
</code></pre><p>The files are added to <code>/tmp/laravel</code> because <a target="_blank" href="https://github.com/composer/composer/issues/1135#issuecomment-10358244">composer projects cannot be created in non-empty folders</a> , so we need to create the project in a temporary location first and move it afterwards.</p>
<p>Since I don't have PHP 8 installed on my laptop, I'll execute the command in the <code>application</code> docker container via</p>
<pre><code>make execute<span class="hljs-operator">-</span>in<span class="hljs-operator">-</span>container DOCKER_SERVICE_NAME<span class="hljs-operator">=</span><span class="hljs-string">"application"</span> COMMAND<span class="hljs-operator">=</span><span class="hljs-string">'composer create-project --prefer-dist laravel/laravel /tmp/laravel "9.*" --no-install --no-scripts'</span>
</code></pre><p>and then move the files into the application directory via</p>
<pre><code>rm <span class="hljs-operator">-</span>rf <span class="hljs-keyword">public</span><span class="hljs-operator">/</span> tests<span class="hljs-operator">/</span> composer.* phpunit.xml
make execute<span class="hljs-operator">-</span>in<span class="hljs-operator">-</span>container DOCKER_SERVICE_NAME<span class="hljs-operator">=</span><span class="hljs-string">"application"</span> COMMAND<span class="hljs-operator">=</span><span class="hljs-string">"bash -c 'mv -n /tmp/laravel/{.*,*} .' &amp;&amp; rm -f /tmp/laravel"</span>
cp .env.example .env
</code></pre><p><strong>Notes</strong></p>
<ul>
<li><code>composer install</code> is skipped via <code>--no-install</code> to avoid having to copy over the <code>vendor/</code> folder
(which is super slow on Docker Desktop)</li>
<li><a target="_blank" href="https://unix.stackexchange.com/a/127713">existing directories cannot be overwritten by <code>mv</code></a> 
thus I remove <code>public/</code> and <code>tests/</code> upfront (as well as the <code>composer</code> and <code>phpunit</code> config 
files)</li>
<li><code>mv</code> uses the <code>-n</code> flag so that existing files like our <code>.editorconfig</code> are not overwritten</li>
<li>I need to use <code>bash -c</code> to run the command in the container because otherwise  <a target="_blank" href="https://github.com/moby/moby/issues/12558#issuecomment-94775867">the <code>*</code> wildcard would have no effect in the container</a> </li>
</ul>
<p>To finalize the installation I need to install the composer dependencies and execute the  <code>create-project</code> scripts defined in  <a target="_blank" href="https://github.com/laravel/laravel/blob/9.x/composer.json#L45"><code>composer.json</code></a>:</p>
<pre><code><span class="hljs-built_in">make</span> composer ARGS=install
<span class="hljs-built_in">make</span> composer ARGS=<span class="hljs-string">"run-script post-create-project-cmd"</span>
</code></pre><p>Since our nginx configuration was already pointing to the <code>public/</code> directory, we can immediately  open <a target="_blank" href="http://127.0.0.1">http://127.0.0.1</a> in the browser and should see the frontpage of  a fresh Laravel installation.</p>

<p><a id="update-the-php-poc"> </a>
</p>
<h2 id="heading-update-the-php-poc">Update the PHP POC</h2>

<p><a id="config"> </a>
</p>
<h3 id="heading-config">config</h3>
<p>We need to update the connection information for the database and the queue (previously  configured via <code>dependencies.php</code>) in the <code>.env</code> file</p>

<p><a id="database-connection"> </a>
</p>
<h4 id="heading-database-connection">database connection</h4>
<pre><code><span class="hljs-attr">DB_CONNECTION</span>=mysql
<span class="hljs-attr">DB_HOST</span>=mysql
<span class="hljs-attr">DB_PORT</span>=<span class="hljs-number">3306</span>
<span class="hljs-attr">DB_DATABASE</span>=application_db
<span class="hljs-attr">DB_USERNAME</span>=root
<span class="hljs-attr">DB_PASSWORD</span>=secret_mysql_root_password
</code></pre>
<p><a id="queue-connection"> </a>
</p>
<h4 id="heading-queue-connection">queue connection</h4>
<pre><code><span class="hljs-attr">QUEUE_CONNECTION</span>=redis

<span class="hljs-attr">REDIS_HOST</span>=redis
<span class="hljs-attr">REDIS_PASSWORD</span>=secret_redis_password
</code></pre>
<p><a id="controllers"> </a>
</p>
<h3 id="heading-controllers">Controllers</h3>
<p>The functionality of the previous <code>public/index.php</code> file now lives in the <code>HomeController</code> at  <code>app/Http/Controllers/HomeController.php</code></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomeController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">DispatchesJobs</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke</span>(<span class="hljs-params">Request $request, QueueManager $queueManager, DatabaseManager $databaseManager</span>): <span class="hljs-title">View</span>
    </span>{
        $jobId = $request-&gt;input(<span class="hljs-string">"dispatch"</span>) ?? <span class="hljs-literal">null</span>;
        <span class="hljs-keyword">if</span> ($jobId !== <span class="hljs-literal">null</span>) {
            $job = <span class="hljs-keyword">new</span> InsertInDbJob($jobId);
            <span class="hljs-keyword">$this</span>-&gt;dispatch($job);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;getView(<span class="hljs-string">"Adding item '<span class="hljs-subst">$jobId</span>' to queue"</span>);
        }

        <span class="hljs-keyword">if</span> ($request-&gt;has(<span class="hljs-string">"queue"</span>)) {

            <span class="hljs-comment">/**
             * <span class="hljs-doctag">@var</span> RedisQueue $redisQueue
             */</span>
            $redisQueue = $queueManager-&gt;connection();
            $redis =  $redisQueue-&gt;getRedis()-&gt;connection();
            $queueItems = $redis-&gt;lRange(<span class="hljs-string">"queues:default"</span>, <span class="hljs-number">0</span>, <span class="hljs-number">99999</span>);

            $content = <span class="hljs-string">"Items in queue\n"</span>.var_export($queueItems, <span class="hljs-literal">true</span>);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;getView($content);
        }

        <span class="hljs-keyword">if</span> ($request-&gt;has(<span class="hljs-string">"db"</span>)) {
            $items = $databaseManager-&gt;select($databaseManager-&gt;raw(<span class="hljs-string">"SELECT * FROM jobs"</span>));

            $content = <span class="hljs-string">"Items in db\n"</span>.var_export($items, <span class="hljs-literal">true</span>);

            <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;getView($content);
        }
        $content = <span class="hljs-string">&lt;&lt;&lt;HTML
            &lt;ul&gt;
                &lt;li&gt;&lt;a href="?dispatch=foo"&gt;Dispatch job 'foo' to the queue.&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href="?queue"&gt;Show the queue.&lt;/a&gt;&lt;/li&gt;
                &lt;li&gt;&lt;a href="?db"&gt;Show the DB.&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
            HTML</span>;

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;getView($content);
    }

    <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getView</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $content</span>): <span class="hljs-title">View</span>
    </span>{
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'home'</span>)-&gt;with([<span class="hljs-string">"content"</span> =&gt; $content]);
    }
}
</code></pre>
<p>Its content is displayed via the <code>home</code> view located at <code>resources/views/home.blade.php</code>:</p>
<pre><code><span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    {<span class="hljs-operator">!</span><span class="hljs-operator">!</span> $content <span class="hljs-operator">!</span><span class="hljs-operator">!</span>}
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre><p>The controller is added as a route in <code>routes/web.php</code>:</p>
<pre><code class="lang-php">Route::get(<span class="hljs-string">'/'</span>, \App\Http\Controllers\HomeController::class)-&gt;name(<span class="hljs-string">"home"</span>);
</code></pre>

<p><a id="commands"> </a>
</p>
<h3 id="heading-commands">Commands</h3>
<p>We will replace the <code>setup.php</code> script with a <code>SetupDbCommand</code> that is located at  <code>app/Commands/SetupDbCommand.php</code></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SetupDbCommand</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Command</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">protected</span> $name = <span class="hljs-string">"app:setup-db"</span>;

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@var</span> string
     */</span>
    <span class="hljs-keyword">protected</span> $description = <span class="hljs-string">"Run the application database setup"</span>;

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOptions</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            [
                <span class="hljs-string">"drop"</span>,
                <span class="hljs-literal">null</span>,
                InputOption::VALUE_NONE,
                <span class="hljs-string">"If given, the existing database tables are dropped and recreated."</span>,
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params"></span>)
    </span>{
        $drop = <span class="hljs-keyword">$this</span>-&gt;option(<span class="hljs-string">"drop"</span>);
        <span class="hljs-keyword">if</span> ($drop) {
            <span class="hljs-keyword">$this</span>-&gt;info(<span class="hljs-string">"Dropping all database tables..."</span>);

            <span class="hljs-keyword">$this</span>-&gt;call(WipeCommand::class);

            <span class="hljs-keyword">$this</span>-&gt;info(<span class="hljs-string">"Done."</span>);
        }

        <span class="hljs-keyword">$this</span>-&gt;info(<span class="hljs-string">"Running database migrations..."</span>);

        <span class="hljs-keyword">$this</span>-&gt;call(MigrateCommand::class);

        <span class="hljs-keyword">$this</span>-&gt;info(<span class="hljs-string">"Done."</span>);
    }
}
</code></pre>
<p>Register it the <code>AppServiceProvider</code> in <code>app/Providers/AppServiceProvider.php</code></p>
<pre><code class="lang-php">    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">register</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">$this</span>-&gt;commands([
            \App\Commands\SetupDbCommand::class
        ]);
    }
</code></pre>
<p>and update the <code>setup-db</code> target in <code>.make/01-00-application-setup.mk</code> to run the <code>artisan</code> Command</p>
<pre><code class="lang-Makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: setup-db</span>
<span class="hljs-section">setup-db: ## Setup the DB tables</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> php artisan app:setup-db <span class="hljs-variable">$(ARGS)</span>;
</code></pre>
<p>We will also create a migration for the <code>jobs</code> table in  <code>database/migrations/2022_02_10_000000_create_jobs_table.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        Schema::create(<span class="hljs-string">'jobs'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">Blueprint $table</span>) </span>{
            $table-&gt;id();
            $table-&gt;string(<span class="hljs-string">'value'</span>);
        });
    }
};
</code></pre>

<p><a id="jobs-and-workers"> </a>
</p>
<h3 id="heading-jobs-and-workers">Jobs and workers</h3>
<p>We will replace the <code>worker.php</code> script with <code>InsertInDbJob</code> located at  <code>app/Jobs/InsertInDbJob.php</code></p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InsertInDbJob</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShouldQueue</span>
</span>{
    <span class="hljs-keyword">use</span> <span class="hljs-title">Dispatchable</span>, <span class="hljs-title">InteractsWithQueue</span>, <span class="hljs-title">Queueable</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__construct</span>(<span class="hljs-params">
        <span class="hljs-keyword">public</span> readonly <span class="hljs-keyword">string</span> $jobId
    </span>) </span>{
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handle</span>(<span class="hljs-params">DatabaseManager $databaseManager</span>)
    </span>{
        $databaseManager-&gt;insert(<span class="hljs-string">"INSERT INTO `jobs`(value) VALUES(?)"</span>, [<span class="hljs-keyword">$this</span>-&gt;jobId]);
    }
}
</code></pre>
<p>though this will "only" handle the insertion part. For the worker itself we will use the native <code>\Illuminate\Queue\Console\WorkCommand</code> via</p>
<pre><code>php artisan queue:<span class="hljs-keyword">work</span>
</code></pre><p>We need to adjust the <code>.docker/images/php/worker/Dockerfile</code> and change</p>
<pre><code><span class="hljs-attribute">ARG</span> PHP_WORKER_COMMAND=<span class="hljs-string">"php <span class="hljs-variable">$APP_CODE_PATH</span>/worker.php"</span>
</code></pre><p>to</p>
<pre><code><span class="hljs-attribute">ARG</span> PHP_WORKER_COMMAND=<span class="hljs-string">"php <span class="hljs-variable">$APP_CODE_PATH</span>/artisan queue:work"</span>
</code></pre><p>Since this change takes place directly in the Dockerfile, we must now rebuild the image </p>
<pre><code>$ make docker<span class="hljs-operator">-</span>build<span class="hljs-operator">-</span>image DOCKER_SERVICE_NAME<span class="hljs-operator">=</span>php<span class="hljs-operator">-</span>worker
</code></pre><p>and restart it</p>
<pre><code>$ <span class="hljs-built_in">make</span> docker-up
</code></pre>
<p><a id="tests"> </a>
</p>
<h3 id="heading-tests">Tests</h3>
<p>I'd also like to take this opportunity to add a <code>Feature</code> test for the <code>HomeController</code> at <code>tests/Feature/App/Http/Controllers/HomeControllerTest.php</code>:</p>
<pre><code class="lang-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomeControllerTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">TestCase</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setUp</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        <span class="hljs-built_in">parent</span>::setUp();

        <span class="hljs-keyword">$this</span>-&gt;setupDatabase();
        <span class="hljs-keyword">$this</span>-&gt;setupQueue();
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@dataProvider</span> __invoke_dataProvider
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test___invoke</span>(<span class="hljs-params"><span class="hljs-keyword">array</span> $params, <span class="hljs-keyword">string</span> $expected</span>): <span class="hljs-title">void</span>
    </span>{
        $urlGenerator = <span class="hljs-keyword">$this</span>-&gt;getDependency(UrlGenerator::class);

        $url = $urlGenerator-&gt;route(<span class="hljs-string">"home"</span>, $params);

        $response = <span class="hljs-keyword">$this</span>-&gt;get($url);

        $response
            -&gt;assertStatus(<span class="hljs-number">200</span>)
            -&gt;assertSee($expected, <span class="hljs-literal">false</span>)
        ;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">__invoke_dataProvider</span>(<span class="hljs-params"></span>): <span class="hljs-title">array</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">"default"</span>           =&gt; [
                <span class="hljs-string">"params"</span>   =&gt; [],
                <span class="hljs-string">"expected"</span> =&gt; <span class="hljs-string">&lt;&lt;&lt;TEXT
                        &lt;li&gt;&lt;a href="?dispatch=foo"&gt;Dispatch job 'foo' to the queue.&lt;/a&gt;&lt;/li&gt;
                        &lt;li&gt;&lt;a href="?queue"&gt;Show the queue.&lt;/a&gt;&lt;/li&gt;
                        &lt;li&gt;&lt;a href="?db"&gt;Show the DB.&lt;/a&gt;&lt;/li&gt;
                    TEXT</span>
                ,
            ],
            <span class="hljs-string">"database is empty"</span> =&gt; [
                <span class="hljs-string">"params"</span>   =&gt; [<span class="hljs-string">"db"</span>],
                <span class="hljs-string">"expected"</span> =&gt; <span class="hljs-string">&lt;&lt;&lt;TEXT
                        Items in db
                    array (
                    )
                    TEXT</span>
                ,
            ],
            <span class="hljs-string">"queue is empty"</span>    =&gt; [
                <span class="hljs-string">"params"</span>   =&gt; [<span class="hljs-string">"queue"</span>],
                <span class="hljs-string">"expected"</span> =&gt; <span class="hljs-string">&lt;&lt;&lt;TEXT
                        Items in queue
                    array (
                    )
                    TEXT</span>
                ,
            ],
        ];
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test_shows_existing_items_in_database</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        $databaseManager = <span class="hljs-keyword">$this</span>-&gt;getDependency(DatabaseManager::class);

        $databaseManager-&gt;insert(<span class="hljs-string">"INSERT INTO `jobs` (id, value) VALUES(1, 'foo');"</span>);

        $urlGenerator = <span class="hljs-keyword">$this</span>-&gt;getDependency(UrlGenerator::class);

        $params = [<span class="hljs-string">"db"</span>];
        $url    = $urlGenerator-&gt;route(<span class="hljs-string">"home"</span>, $params);

        $response = <span class="hljs-keyword">$this</span>-&gt;get($url);

        $expected = <span class="hljs-string">&lt;&lt;&lt;TEXT
                Items in db
            array (
              0 =&gt; 
              (object) array(
                 'id' =&gt; 1,
                 'value' =&gt; 'foo',
              ),
            )
            TEXT</span>;

        $response
            -&gt;assertStatus(<span class="hljs-number">200</span>)
            -&gt;assertSee($expected, <span class="hljs-literal">false</span>)
        ;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test_shows_existing_items_in_queue</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        $queueManager = <span class="hljs-keyword">$this</span>-&gt;getDependency(QueueManager::class);

        $job = <span class="hljs-keyword">new</span> InsertInDbJob(<span class="hljs-string">"foo"</span>);
        $queueManager-&gt;push($job);

        $urlGenerator = <span class="hljs-keyword">$this</span>-&gt;getDependency(UrlGenerator::class);

        $params = [<span class="hljs-string">"queue"</span>];
        $url    = $urlGenerator-&gt;route(<span class="hljs-string">"home"</span>, $params);

        $response = <span class="hljs-keyword">$this</span>-&gt;get($url);

        $expectedJobsCount = <span class="hljs-string">&lt;&lt;&lt;TEXT
                Items in queue
            array (
              0 =&gt; '{
            TEXT</span>;

        $expected = <span class="hljs-string">&lt;&lt;&lt;TEXT
            \\\\"jobId\\\\";s:3:\\\\"foo\\\\";
            TEXT</span>;

        $response
            -&gt;assertStatus(<span class="hljs-number">200</span>)
            -&gt;assertSee($expectedJobsCount, <span class="hljs-literal">false</span>)
            -&gt;assertSee($expected, <span class="hljs-literal">false</span>)
        ;
    }
}
</code></pre>
<p>The test checks the database as well as the queue and uses the helper methods  <code>$this-&gt;setupDatabase()</code> and <code>$this-&gt;setupQueue()</code> that I defined in the base test case at <code>tests/TestCase.php</code> as follows</p>
<pre><code class="lang-php">   <span class="hljs-comment">/**
     * <span class="hljs-doctag">@template</span> T
     * <span class="hljs-doctag">@param</span> class-string&lt;T&gt; $className
     * <span class="hljs-doctag">@return</span> T
     */</span>
    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getDependency</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> $className</span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;app-&gt;get($className);
    }

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setupDatabase</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        $databaseManager = <span class="hljs-keyword">$this</span>-&gt;getDependency(DatabaseManager::class);

        $actualConnection  = $databaseManager-&gt;getDefaultConnection();
        $testingConnection = <span class="hljs-string">"testing"</span>;
        <span class="hljs-keyword">if</span> ($actualConnection !== $testingConnection) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">RuntimeException</span>(<span class="hljs-string">"Database tests are only allowed to run on default connection '<span class="hljs-subst">$testingConnection</span>'. The current default connection is '<span class="hljs-subst">$actualConnection</span>'."</span>);
        }

        <span class="hljs-keyword">$this</span>-&gt;ensureDatabaseExists($databaseManager);

        <span class="hljs-keyword">$this</span>-&gt;artisan(SetupDbCommand::class, [<span class="hljs-string">"--drop"</span> =&gt; <span class="hljs-literal">true</span>]);
    }

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setupQueue</span>(<span class="hljs-params"></span>): <span class="hljs-title">void</span>
    </span>{
        $queueManager = <span class="hljs-keyword">$this</span>-&gt;getDependency(QueueManager::class);

        $actualDriver  = $queueManager-&gt;getDefaultDriver();
        $testingDriver = <span class="hljs-string">"testing"</span>;
        <span class="hljs-keyword">if</span> ($actualDriver !== $testingDriver) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">RuntimeException</span>(<span class="hljs-string">"Queue tests are only allowed to run on default driver '<span class="hljs-subst">$testingDriver</span>'. The current default driver is '<span class="hljs-subst">$actualDriver</span>'."</span>);
        }

        <span class="hljs-keyword">$this</span>-&gt;artisan(ClearCommand::class);
    }

    <span class="hljs-keyword">protected</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ensureDatabaseExists</span>(<span class="hljs-params">DatabaseManager $databaseManager</span>): <span class="hljs-title">void</span>
    </span>{
        $connection = $databaseManager-&gt;connection();

        <span class="hljs-keyword">try</span> {
            $connection-&gt;getPdo();
        } <span class="hljs-keyword">catch</span> (PDOException $e) {
            <span class="hljs-comment">// e.g. SQLSTATE[HY000] [1049] Unknown database 'testing'</span>
            <span class="hljs-keyword">if</span> ($e-&gt;getCode() !== <span class="hljs-number">1049</span>) {
                <span class="hljs-keyword">throw</span> $e;
            }
            $config             = $connection-&gt;getConfig();
            $config[<span class="hljs-string">"database"</span>] = <span class="hljs-string">""</span>;

            $connector = <span class="hljs-keyword">new</span> MySqlConnector();
            $pdo       = $connector-&gt;connect($config);
            $database  = $connection-&gt;getDatabaseName();
            $pdo-&gt;exec(<span class="hljs-string">"CREATE DATABASE IF NOT EXISTS `<span class="hljs-subst">{$database}</span>`;"</span>);
        }
    }
</code></pre>
<p>The methods ensure that the tests are only executed if the proper database connection and queue  driver is configured. This is done through environment variables and I like using <a target="_blank" href="https://laravel.com/docs/9.x/testing#the-env-testing-environment-file">a dedicated <code>.env</code> file located at <code>.env.testing</code></a>   for all testing <code>ENV</code> values instead of defining them in the <code>phpunit.xml</code> config file via <code>&lt;env&gt;</code>  elements:</p>
<pre><code class="lang-dotenv"># File: .env.testing

DB_CONNECTION=testing
DB_DATABASE=testing
QUEUE_CONNECTION=testing
REDIS_DB=1000
</code></pre>
<p>The corresponding connections have to be configured in the <code>config</code> files</p>
<pre><code class="lang-php"><span class="hljs-comment"># File: config/database.php</span>

<span class="hljs-keyword">return</span> [
<span class="hljs-comment">// ...</span>
    <span class="hljs-string">'connections'</span> =&gt; [
<span class="hljs-comment">// ...</span>
        <span class="hljs-string">'testing'</span> =&gt; [
            <span class="hljs-string">'driver'</span> =&gt; <span class="hljs-string">'mysql'</span>,
            <span class="hljs-string">'url'</span> =&gt; env(<span class="hljs-string">'DATABASE_URL'</span>),
            <span class="hljs-string">'host'</span> =&gt; env(<span class="hljs-string">'DB_HOST'</span>),
            <span class="hljs-string">'port'</span> =&gt; env(<span class="hljs-string">'DB_PORT'</span>, <span class="hljs-string">'3306'</span>),
            <span class="hljs-string">'database'</span> =&gt; env(<span class="hljs-string">'DB_DATABASE'</span>, <span class="hljs-string">'testing'</span>),
            <span class="hljs-string">'username'</span> =&gt; env(<span class="hljs-string">'DB_USERNAME'</span>),
            <span class="hljs-string">'password'</span> =&gt; env(<span class="hljs-string">'DB_PASSWORD'</span>, <span class="hljs-string">''</span>),
            <span class="hljs-string">'unix_socket'</span> =&gt; env(<span class="hljs-string">'DB_SOCKET'</span>, <span class="hljs-string">''</span>),
            <span class="hljs-string">'charset'</span> =&gt; <span class="hljs-string">'utf8mb4'</span>,
            <span class="hljs-string">'collation'</span> =&gt; <span class="hljs-string">'utf8mb4_unicode_ci'</span>,
            <span class="hljs-string">'prefix'</span> =&gt; <span class="hljs-string">''</span>,
            <span class="hljs-string">'prefix_indexes'</span> =&gt; <span class="hljs-literal">true</span>,
            <span class="hljs-string">'strict'</span> =&gt; <span class="hljs-literal">true</span>,
            <span class="hljs-string">'engine'</span> =&gt; <span class="hljs-literal">null</span>,
            <span class="hljs-string">'options'</span> =&gt; extension_loaded(<span class="hljs-string">'pdo_mysql'</span>) ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA =&gt; env(<span class="hljs-string">'MYSQL_ATTR_SSL_CA'</span>),
            ]) : [],
        ],
    ],
<span class="hljs-comment">// ...</span>
    <span class="hljs-string">'redis'</span> =&gt; [
<span class="hljs-comment">// ...</span>
        <span class="hljs-string">'testing'</span> =&gt; [
            <span class="hljs-string">'url'</span> =&gt; env(<span class="hljs-string">'REDIS_URL'</span>),
            <span class="hljs-string">'host'</span> =&gt; env(<span class="hljs-string">'REDIS_HOST'</span>, <span class="hljs-string">'127.0.0.1'</span>),
            <span class="hljs-string">'password'</span> =&gt; env(<span class="hljs-string">'REDIS_PASSWORD'</span>),
            <span class="hljs-string">'port'</span> =&gt; env(<span class="hljs-string">'REDIS_PORT'</span>, <span class="hljs-string">'6379'</span>),
            <span class="hljs-string">'database'</span> =&gt; env(<span class="hljs-string">'REDIS_DB'</span>, <span class="hljs-string">'1000'</span>),
        ],
    ],
];
</code></pre>
<pre><code class="lang-php"><span class="hljs-comment"># File: config/queue.php</span>

<span class="hljs-keyword">return</span> [
<span class="hljs-comment">// ...</span>

    <span class="hljs-string">'connections'</span> =&gt; [
<span class="hljs-comment">// ...</span>
        <span class="hljs-string">'testing'</span> =&gt; [
            <span class="hljs-string">'driver'</span> =&gt; <span class="hljs-string">'redis'</span>,
            <span class="hljs-string">'connection'</span> =&gt; <span class="hljs-string">'testing'</span>, <span class="hljs-comment">// =&gt; refers to the "database.redis.testing" config entry</span>
            <span class="hljs-string">'queue'</span> =&gt; env(<span class="hljs-string">'REDIS_QUEUE'</span>, <span class="hljs-string">'default'</span>),
            <span class="hljs-string">'retry_after'</span> =&gt; <span class="hljs-number">90</span>,
            <span class="hljs-string">'block_for'</span> =&gt; <span class="hljs-literal">null</span>,
            <span class="hljs-string">'after_commit'</span> =&gt; <span class="hljs-literal">false</span>,
        ],
    ],
];
</code></pre>
<p>The tests can be executed via <code>make test</code></p>
<pre><code>$ make test
ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker vendor<span class="hljs-operator">/</span>bin<span class="hljs-operator">/</span>phpunit <span class="hljs-operator">-</span>c phpunit.xml
PHPUnit <span class="hljs-number">9.5</span><span class="hljs-number">.13</span> by Sebastian Bergmann and contributors.

.......                                                             <span class="hljs-number">7</span> <span class="hljs-operator">/</span> <span class="hljs-number">7</span> (<span class="hljs-number">100</span><span class="hljs-operator">%</span>)

Time: 00:02<span class="hljs-number">.709</span>, Memory: <span class="hljs-number">28.00</span> MB

OK (<span class="hljs-number">7</span> tests, <span class="hljs-number">13</span> assertions)
</code></pre>
<p><a id="makefile-updates"> </a>
</p>
<h2 id="heading-makefile-updates">Makefile updates</h2>

<p><a id="clearing-the-queue"> </a>
</p>
<h3 id="heading-clearing-the-queue">Clearing the queue</h3>
<p>For convenience while testing I added a make target to clear all items from the queue in  <code>.make/01-01-application-commands.mk</code></p>
<pre><code class="lang-Makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: clear-queue</span>
<span class="hljs-section">clear-queue: ## Clear the job queue</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> php artisan queue:clear <span class="hljs-variable">$(ARGS)</span>
</code></pre>

<p><a id="running-the-poc"> </a>
</p>
<h2 id="heading-running-the-poc">Running the POC</h2>
<p>Since the POC only uses <code>make</code> targets and we basically just "refactored" them, there is no  modification necessary to make the existing <code>test.sh</code> work:</p>
<pre><code>$ bash test.sh


  Building the docker setup


<span class="hljs-comment">//...</span>


  Starting the docker setup


<span class="hljs-comment">//...</span>


  Clearing DB


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application application php artisan app:setup<span class="hljs-operator">-</span>db <span class="hljs-operator">-</span><span class="hljs-operator">-</span>drop;
Dropping all database tables...
Dropped all tables successfully.
Done.
Running database migrations...
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (<span class="hljs-number">64</span>.04ms)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (<span class="hljs-number">50</span>.06ms)
Migrating: 2019_08_19_000000_create_failed_jobs_table
Migrated:  2019_08_19_000000_create_failed_jobs_table (<span class="hljs-number">58</span>.61ms)
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated:  2019_12_14_000001_create_personal_access_tokens_table (<span class="hljs-number">94</span>.03ms)
Migrating: 2022_02_10_000000_create_jobs_table
Migrated:  2022_02_10_000000_create_jobs_table (<span class="hljs-number">31</span>.85ms)
Done.


  Stopping workers


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker supervisorctl stop worker:<span class="hljs-operator">*</span>;
worker:worker_00: stopped
worker:worker_01: stopped
worker:worker_02: stopped
worker:worker_03: stopped


  Ensuring that queue and db are empty


<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Items in queue
array (
)
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Items in db
array (
)
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>


  Dispatching a job <span class="hljs-string">'foo'</span>


<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Adding item <span class="hljs-string">'foo'</span> to queue
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>


  Asserting the job <span class="hljs-string">'foo'</span> <span class="hljs-keyword">is</span> on the queue


<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Items in queue
array (
  <span class="hljs-number">0</span> <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-string">'{"uuid":"7ea63590-2a86-4739-abf8-8a059d41bd60","displayName":"App\\\\Jobs\\\\InsertInDbJob","job":"Illuminate\\\\Queue\\\\CallQueuedHandler@call","maxTries":null,"maxExceptions":null,"failOnTimeout":false,"backoff":null,"timeout":null,"retryUntil":null,"data":{"commandName":"App\\\\Jobs\\\\InsertInDbJob","command":"O:22:\\"App\\\\Jobs\\\\InsertInDbJob\\":11:{s:5:\\"jobId\\";s:3:\\"foo\\";s:3:\\"job\\";N;s:10:\\"connection\\";N;s:5:\\"queue\\";N;s:15:\\"chainConnection\\";N;s:10:\\"chainQueue\\";N;s:19:\\"chainCatchCallbacks\\";N;s:5:\\"delay\\";N;s:11:\\"afterCommit\\";N;s:10:\\"middleware\\";a:0:{}s:7:\\"chained\\";a:0:{}}"},"id":"I3k5PNyGZc6Z5XWCC4gt0qtSdqUZ84FU","attempts":0}'</span>,
)
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>


  Starting the workers


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker supervisorctl start worker:<span class="hljs-operator">*</span>;
worker:worker_00: started
worker:worker_01: started
worker:worker_02: started
worker:worker_03: started


  Asserting the queue <span class="hljs-keyword">is</span> <span class="hljs-built_in">now</span> empty


<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Items in queue
array (
)
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>


  Asserting the db <span class="hljs-built_in">now</span> contains the job <span class="hljs-string">'foo'</span>


<span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span>DOCTYPE html<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>html<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>head<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>meta charset<span class="hljs-operator">=</span><span class="hljs-string">"utf-8"</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>head<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>body<span class="hljs-operator">&gt;</span>
    Items in db
array (
  <span class="hljs-number">0</span> <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
  (object) array(
     <span class="hljs-string">'id'</span> <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-number">1</span>,
     <span class="hljs-string">'value'</span> <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-string">'foo'</span>,
  ),
)
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>html<span class="hljs-operator">&gt;</span>
</code></pre>
<p><a id="wrapping-up"> </a>
</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. Laravel 9 should now be up and running on the previously set up docker infrastructure.</p>
<p>In the next part of this tutorial, we will <a target="_blank" href="https://www.pascallandau.com/blog/php-qa-tools-make-docker/">Set up PHP QA tools and control them via make</a>.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)</p>
<p>;</p>
]]></content:encoded></item><item><title><![CDATA[How to build a Docker development setup for PHP Projects [Tutorial Part 1]]]></title><description><![CDATA[This article appeared first on at How to build a Docker development setup for PHP Projects [Tutorial Part 1] In this part of my tutorial series on…]]></description><link>https://pascallandau.hashnode.dev/how-to-build-a-docker-development-setup-for-php-projects-tutorial-part-1</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/how-to-build-a-docker-development-setup-for-php-projects-tutorial-part-1</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Mon, 27 Jun 2022 07:36:08 GMT</pubDate><content:encoded><![CDATA[<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/">How to build a Docker development setup for PHP Projects [Tutorial Part 1]</a></p><p></p>
<hr />

<div class="panel panel-default">
  <div class="panel-heading">
    <strong>Caution</strong>
  </div>
  <div class="panel-body bg-danger">
    There is a <strong>follow-up version</strong> of this article available that was published 
    in <strong>2022</strong> - please make sure to read that as well:
    <br />
    <a href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022</a>
  </div>
</div>

<p>In this part of my tutorial series on developing PHP on Docker we'll lay the fundamentals to build a complete development infrastructure and explain how to "structure" the Docker setup as part of a PHP project. Structure as in </p>
<ul>
<li>folder structure ("what to put where")</li>
<li>Dockerfile templates</li>
<li>solving common problems (file permissions, runtime configuration, ...)</li>
</ul>
<p>We will also create a minimal container setup consisting of php-fpm, nginx and a workspace container that we  refactor from the previous parts of this tutorial.</p>
<p>{% youtube YYI5mTjFDuA %}</p>
<p><strong>All code samples are publicly available</strong> in my  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.  The branch for this tutorial is  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part_3_structuring-the-docker-setup-for-php-projects">part_3_structuring-the-docker-setup-for-php-projects</a>.</p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/">Setting up PhpStorm with Xdebug for local development on Docker</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>
<h2 id="heading-table-of-contents">Table of contents</h2>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#structuring-the-repository">Structuring the repository</a><ul>
<li><a href="#the-docker-folder">The .docker folder</a></li>
<li><a href="#shared-folder">The <code>.shared</code> folder</a></li>
<li><a href="#"><code>docker-test.sh</code></a></li>
<li><a href="#env-example-and-docker-compose-yml"><code>.env.example</code> and <code>docker-compose.yml</code></a></li>
<li><a href="#the-makefile">The Makefile</a></li>
</ul>
</li>
<li><a href="#defining-services-php-fpm-nginx-and-workspace">Defining services: php-fpm, nginx and workspace</a><ul>
<li><a href="#php-fpm">php-fpm</a><ul>
<li><a href="#modifying-the-pool-configuration">Modifying the pool configuration</a></li>
<li><a href="#custom-entrypoint">Custom ENTRYPOINT</a></li>
</ul>
</li>
<li><a href="#nginx">nginx</a></li>
<li><a href="#workspace-formerly-php-cli">workspace (formerly php-cli)</a></li>
</ul>
</li>
<li><a href="#setting-up-docker-compose">Setting up docker-compose</a> <ul>
<li><a href="#docker-compose-yml">docker-compose.yml</a></li>
<li><a href="#env-example">.env.example</a></li>
<li><a href="#building-and-running-the-containers">Building and running the containers</a></li>
<li><a href="#testing-if-everything-works">Testing if everything works</a></li>
</ul>
</li>
<li><a href="#makefile-and-bashrc">Makefile and <code>.bashrc</code></a><ul>
<li><a href="#using-make-as-central-entry-point">Using <code>make</code> as central entry point</a></li>
<li><a href="#install-make-on-windows-mingw">Install make on Windows (MinGW)</a></li>
<li><a href="#easy-container-access-via-din-bashrc-helper">Easy container access via <code>din</code> .bashrc helper</a></li>
</ul>
</li>
<li><a href="#fundamentals-on-building-the-containers">Fundamentals on building the containers</a><ul>
<li><a href="#understanding-build-context">Understanding build context</a></li>
<li><a href="#dockerfile-template">Dockerfile template</a></li>
<li><a href="#setting-the-timezone">Setting the timezone</a></li>
<li><a href="#synchronizing-file-and-folder-ownership-on-shared-volumes">Synchronizing file and folder ownership on shared volumes</a></li>
<li><a href="#modifying-configuration-files">Modifying configuration files</a><ul>
<li><a href="#providing-additional-config-files">Providing additional config files</a></li>
<li><a href="#changing-non-static-values">Changing non-static values</a></li>
</ul>
</li>
<li><a href="#installing-php-extensions">Installing php extensions</a></li>
<li><a href="#installing-common-software">Installing common software</a></li>
<li><a href="#cleaning-up">Cleaning up</a></li>
<li><a href="#using-entrypoint-for-pre-run-configuration">Using <code>ENTRYPOINT</code> for pre-run configuration</a><ul>
<li><a href="#providing-host-docker-internal-for-linux-host-systems">Providing <code>host.docker.internal</code> for linux host systems</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#wrapping-up">Wrapping up</a></li>
</ul>
<h2 id="heading-introduction"><a id="introduction"></a>Introduction</h2>
<p>When I started my current role as Head of Marketing Technology at ABOUT YOU back in 2016, we heavily relied on <a target="_blank" href="https://www.pascallandau.com/blog/phpstorm-with-vagrant-using-laravel-homestead-on-windows-10/">Vagrant (namely: Homestead) as our development infrastructure</a>.  Though that was much better than  working on our local machines, we've run into a couple of problems along the way (e.g. diverging software, bloated images, slow starting times, complicated readme for onboarding, upgrading php, ...).</p>
<p>Today, everything that we need for the infrastructure is under source control and committed in the same repository that we use for our main application. In effect we get <strong>the same infrastructure for every developer</strong> including automatic updates "for free". It is extremely easy to tinker around with updates / new tools due to the ephemeral nature of docker as tear down and rebuild only take one command and a couple of minutes.</p>
<p>To get a feeling for how the process <em>feels</em> like, simply execute the following commands.</p>
<pre><code>git clone https:<span class="hljs-comment">//github.com/paslandau/docker-php-tutorial.git</span>
cd docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial
git checkout part_3_structuring<span class="hljs-operator">-</span>the<span class="hljs-operator">-</span>docker<span class="hljs-operator">-</span>setup<span class="hljs-operator">-</span><span class="hljs-keyword">for</span><span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>projects
make docker<span class="hljs-operator">-</span>clean
make docker<span class="hljs-operator">-</span>init
make docker<span class="hljs-operator">-</span>build<span class="hljs-operator">-</span><span class="hljs-keyword">from</span><span class="hljs-operator">-</span>scratch
make docker<span class="hljs-operator">-</span>test
</code></pre><p>You should now have a running docker environment to develop PHP on docker (unless  <a class="post-section-overview" href="#building-and-running-the-containers">something is blocking your port 80/443</a> or <a class="post-section-overview" href="#install-make-on-windows-mingw">you don't have make installed</a>
;))</p>
<h2 id="heading-structuring-the-repository"><a id="structuring-the-repository"></a>Structuring the repository</h2>
<p>While playing around with docker I've tried different ways to "structure" files and folders and ended up with the following concepts:</p>
<ul>
<li>everything related to docker is <strong>placed in a <code>.docker</code> directory on on the same level as the main application</strong></li>
<li>in this directory<ul>
<li>each service gets its own subdirectory for configuration</li>
<li>is a <strong><code>.shared</code> folder containing scripts and configuration</strong> required by multiple services</li>
<li>is an <strong><code>.env.example</code></strong> file containing variables for the <strong><code>docker-compose.yml</code></strong></li>
<li>is a <strong><code>docker-test.sh</code></strong> file containing high level tests to validate the docker containers</li>
</ul>
</li>
<li>a <strong>Makefile</strong> with common instructions to control Docker is placed in the repository root</li>
</ul>
<p>The result looks roughly like this: </p>
<pre><code><span class="hljs-operator">&lt;</span>project<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── .docker/
<span class="hljs-operator">|</span>   ├── .shared/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── config<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── scripts<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   ├── php<span class="hljs-operator">-</span>fpm<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── Dockerfile
<span class="hljs-operator">|</span>   ├── ... <span class="hljs-operator">&lt;</span>additional services<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   ├── .env.example
<span class="hljs-operator">|</span>   ├── docker<span class="hljs-operator">-</span>compose.yml
<span class="hljs-operator">|</span>   └── docker<span class="hljs-operator">-</span>test.sh
├── Makefile
├── index.php
└──  ... <span class="hljs-operator">&lt;</span>additional app files<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
</code></pre><h3 id="heading-the-docker-folder"><a id="the-docker-folder"></a>The .docker folder</h3>
<p>As I mentioned, for me it makes a lot of sense to keep the <strong>infrastructure definition close to the codebase</strong>, because it is immediately available to every developer. For bigger projects with multiple components there will be a code-infrastructure-coupling anyways  (e.g. in my experience it is usually not possible to simply switch MySQL for PostgreSQL without any other changes)  and for a library it is a very convenient (although opinionated) way to get started. </p>
<p>I personally find it rather  frustrating when I want to contribute to an open source project but find myself spending a significant amount of time setting the environment up correctly instead of being able to just work on the code.</p>
<p>Ymmv, though (e.g. because you don't want everybody with write access to your app repo also to be able to change your  infrastructure code). We actually went a different route previously and had a second repository ("-inf")  that would contain the contents of the <code>.docker</code> folder: </p>
<pre><code><span class="hljs-operator">&lt;</span>project<span class="hljs-operator">-</span>inf<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── .shared/
<span class="hljs-operator">|</span>   ├── config<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   └── scripts<span class="hljs-operator">/</span>
├── php<span class="hljs-operator">-</span>fpm<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   └── Dockerfile
├── ... <span class="hljs-operator">&lt;</span>additional services<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── .env.example
└──  docker<span class="hljs-operator">-</span>compose.yml

<span class="hljs-operator">&lt;</span>project<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── index.php
└──  ... <span class="hljs-operator">&lt;</span>additional app files<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
</code></pre><p>Worked as well, but we often ran into situations where  the contents of the repo would be stale for some devs, plus it was simply additional overhead with not other benefits  to us at that point. Maybe <a target="_blank" href="https://medium.com/@porteneuve/mastering-git-submodules-34c65e940407">git submodules</a> will enable us to get the best of both worlds - I'll blog about it once we try ;)</p>
<h3 id="heading-the-shared-folder"><a id="shared-folder"></a>The <code>.shared</code> folder</h3>
<p>When dealing with multiple services, chances are high that some of those services will be configured similarly, e.g. for</p>
<ul>
<li>installing common software </li>
<li>setting up unix users (with the same ids)</li>
<li>configuration (think php-cli for workers and php-fpm for web requests)</li>
</ul>
<p>To avoid duplication, I place scripts (simple bash files) and config files in the <code>.shared</code> folder and make it available in the build context for each service. I'll explain the process in more detail under  <a class="post-section-overview" href="#understanding-build-context">providing the correct build context</a>.</p>
<h3 id="heading-docker-testsh"><a id></a><code>docker-test.sh</code></h3>
<p>Is really just a simple bash script that includes some high level tests to make sure that the containers are built correctly. See section <a class="post-section-overview" href="#testing-if-everything-works">Testing if everything works</a>.</p>
<h3 id="heading-envexample-and-docker-composeyml"><a id="env-example-and-docker-compose-yml"></a><code>.env.example</code> and <code>docker-compose.yml</code></h3>
<p><code>docker-compose</code> uses a <a target="_blank" href="https://docs.docker.com/compose/environment-variables/#the-env-file"><code>.env</code> file</a> for a convenient way to define and  <a target="_blank" href="https://docs.docker.com/compose/compose-file/#variable-substitution"><code>substitute environment variables</code></a>.  Since this <code>.env</code> file is environment specific, it is <strong>NOT</strong>
part of the repository (i.e. ignored via <code>.gitignore</code>). Instead, we provide a <code>.env.example</code> file that contains  the required environment variables including reasonable default values. A new dev would usually run  <code>cp .env.example .env</code> after checking out the repository for the first time.  See section <a class="post-section-overview" href="#env-example">.env.example</a>.</p>
<h3 id="heading-the-makefile-make-and-makefiles"><a id="the-makefile"></a>The Makefile <code>make</code> and <code>Makefile</code>s</h3>
<p>are among those things that I've heard about occasionally but never really cared to  understand (mostly because I associated them with C). Boy, did I miss out. I was comparing different strategies to provide code quality tooling (style checkers, static analyzers, tests, ...) and went from custom bash scripts over <a target="_blank" href="https://getcomposer.org/doc/articles/scripts.md">composer scripts</a> to finally end up at <code>Makefile</code>s.</p>
<p>The <code>Makefile</code> serves as a central entry point and simplifies the management of the docker containers, e.g. for (re-)building, starting, stopping, logging in, etc. See section <a class="post-section-overview" href="#makefile-and-bashrc">Makefile and .bashrc</a>.</p>
<h2 id="heading-defining-services-php-fpm-nginx-and-workspace"><a id="defining-services-php-fpm-nginx-and-workspace"></a>Defining services: php-fpm, nginx and workspace</h2>
<p>Let's have a look at a real example and "refactor" the  <a class="post-section-overview" href="#workspace-formerly-php-cli">php-cli</a>, <a class="post-section-overview" href="#php-fpm">php-fpm</a> and <a class="post-section-overview" href="#nginx">nginx</a> containers from the <a target="_blank" href="https://www.pascallandau.com/blog/php-php-fpm-and-nginx-on-docker-in-windows-10/">first part of this tutorial series</a>. </p>
<p>This is the folder structure:</p>
<pre><code><span class="hljs-operator">&lt;</span>project<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── .docker/
<span class="hljs-operator">|</span>   ├── .shared/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── config<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── php<span class="hljs-operator">/</span> 
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>       └── conf.d/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>           └── zz<span class="hljs-operator">-</span>app.ini
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── scripts<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>       └── docker<span class="hljs-operator">-</span>entrypoint<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>           └── resolve<span class="hljs-operator">-</span>docker<span class="hljs-operator">-</span>host<span class="hljs-operator">-</span>ip.sh
<span class="hljs-operator">|</span>   ├── nginx<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── sites<span class="hljs-operator">-</span>available<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── default.conf
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── Dockerfile
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── nginx.conf
<span class="hljs-operator">|</span>   ├── php<span class="hljs-operator">-</span>fpm<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── php<span class="hljs-operator">-</span>fpm.d/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── pool.conf
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── Dockerfile
<span class="hljs-operator">|</span>   ├── workspace<span class="hljs-operator">/</span> (formerly php<span class="hljs-operator">-</span>cli)
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── .ssh/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── insecure_id_rsa
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── insecure_id_rsa.pub
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── Dockerfile
<span class="hljs-operator">|</span>   ├── .env.example
<span class="hljs-operator">|</span>   ├── docker<span class="hljs-operator">-</span>compose.yml
<span class="hljs-operator">|</span>   └── docker<span class="hljs-operator">-</span>test.sh
├── Makefile
└── index.php
</code></pre><h3 id="heading-php-fpm"><a id="php-fpm"></a>php-fpm</h3>
<p>Click here to <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/php-fpm/Dockerfile">see the full php-fpm Dockerfile</a>.</p>
<p>Since we will be having two PHP containers, we need to place the common .ini settings in the <code>.shared</code> directory.</p>
<pre><code><span class="hljs-operator">|</span>   ├── .shared/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── config<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── php<span class="hljs-operator">/</span> 
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>       └── conf.d/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>           └── zz<span class="hljs-operator">-</span>app.ini
</code></pre><p>For now, <code>zz-app.ini</code> will only contain our  <a target="_blank" href="https://www.scalingphpbook.com/blog/2014/02/14/best-zend-opcache-settings.html">opcache setup</a>:</p>
<pre><code>; enable opcache
opcache.enable_cli <span class="hljs-operator">=</span> <span class="hljs-number">1</span>
opcache.enable <span class="hljs-operator">=</span> <span class="hljs-number">1</span>
opcache.fast_shutdown <span class="hljs-operator">=</span> <span class="hljs-number">1</span>
; revalidate everytime (effectively disabled <span class="hljs-keyword">for</span> development)
opcache.validate_timestamps <span class="hljs-operator">=</span> <span class="hljs-number">0</span>
</code></pre><p>The pool configuration is only relevant for php-fpm, so it goes in the directory of the service. Btw. I highly  recommend <a target="_blank" href="https://serversforhackers.com/c/lemp-php-fpm-config">this video on PHP-FPM Configuration</a> if your  php-fpm foo isn't already over 9000.</p>
<pre><code><span class="hljs-operator">|</span>   ├── php<span class="hljs-operator">-</span>fpm<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── php<span class="hljs-operator">-</span>fpm.d/
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── pool.conf
</code></pre><h4 id="heading-modifying-the-pool-configuration"><a id="modifying-the-pool-configuration"></a>Modifying the pool configuration</h4>
<p>We're using the <a class="post-section-overview" href="#changing-non-static-values"><code>modify_config.sh</code> script</a> to set the user and group that owns the php-fpm processes.</p>
<pre><code><span class="hljs-comment"># php-fpm pool config</span>
COPY ${SERVICE_DIR}/php-fpm.d/* <span class="hljs-regexp">/usr/local</span><span class="hljs-regexp">/etc/php</span>-fpm.d
RUN /tmp/scripts/modify_config.sh /usr/local/etc/php-fpm.d/zz-default.conf \
    <span class="hljs-string">"__APP_USER"</span> \
    <span class="hljs-string">"${APP_USER}"</span> \
 &amp;&amp; <span class="hljs-regexp">/tmp/scripts</span><span class="hljs-regexp">/modify_config.sh /usr</span><span class="hljs-regexp">/local/etc</span><span class="hljs-regexp">/php-fpm.d/zz</span>-default.conf \
    <span class="hljs-string">"__APP_GROUP"</span> \
    <span class="hljs-string">"${APP_GROUP}"</span> \
;
</code></pre><h4 id="heading-custom-entrypoint"><a id="custom-entrypoint"></a>Custom ENTRYPOINT</h4>
<p>Since php-fpm needs to be debuggable, we need to ensure that the <code>host.docker.internal</code> DNS entry exists, so we'll use the <a class="post-section-overview" href="#providing-host-docker-internal-for-linux-host-systems">corresponding ENTRYPOINT</a> to do that.</p>
<pre><code><span class="hljs-comment"># entrypoint</span>
RUN mkdir -p <span class="hljs-regexp">/bin/docker-entrypoint/</span> \
 &amp;&amp; cp <span class="hljs-regexp">/tmp/scripts/docker-entrypoint/</span>* <span class="hljs-regexp">/bin/docker-entrypoint/</span> \
 &amp;&amp; chmod +x -R <span class="hljs-regexp">/bin/docker-entrypoint/</span> \
;

ENTRYPOINT [<span class="hljs-string">"/bin/docker-entrypoint/resolve-docker-host-ip.sh"</span>,<span class="hljs-string">"php-fpm"</span>]
</code></pre><h3 id="heading-nginx"><a id="nginx"></a>nginx</h3>
<p>Click here to <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/nginx/Dockerfile">see the full nginx Dockerfile</a>.</p>
<p>The nginx setup is even simpler. There is no shared config, so that everything we need resides in </p>
<pre><code><span class="hljs-operator">|</span>   ├── nginx<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── sites<span class="hljs-operator">-</span>available<span class="hljs-operator">/</span>
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── default.conf
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── Dockerfile
<span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── nginx.conf
</code></pre><p>Please note, that nginx only has the <code>nginx.conf</code> file for configuration (i.e. there is no <code>conf.d</code> directory or so), so we need to define the <strong>full</strong> config in there. </p>
<pre><code><span class="hljs-attribute">user</span> __APP_USER __APP_GROUP;
<span class="hljs-attribute">worker_processes</span> <span class="hljs-number">4</span>;
<span class="hljs-attribute">pid</span> /run/nginx.pid;
<span class="hljs-attribute">daemon</span> <span class="hljs-literal">off</span>;

<span class="hljs-section">http</span> {
  <span class="hljs-comment"># ...</span>

  <span class="hljs-attribute">include</span> /etc/nginx/sites-available/<span class="hljs-regexp">*.conf</span>;

  <span class="hljs-comment"># ...</span>
}
</code></pre><p>There are two things to note:</p>
<ul>
<li>user and group are modified dynamically</li>
<li>we specify <code>/etc/nginx/sites-available/</code> as the directory that holds the config files for the individual files via
<code>include /etc/nginx/sites-available/*.conf;</code>
 We need to keep the last point in mind, because we must use the same directory in the Dockerfile:</li>
</ul>
<pre><code><span class="hljs-comment"># nginx app config</span>
COPY ${SERVICE_DIR}/sites-available/* <span class="hljs-regexp">/etc/nginx</span><span class="hljs-regexp">/sites-available/</span>
</code></pre><p>The site's config file  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/nginx/sites-available/default.conf"><code>default.conf</code></a>  has a variable (<code>__NGINX_ROOT</code>) for the <code>root</code> directive and we "connect" it with the fpm-container via  <code>fastcgi_pass php-fpm:9000;</code></p>
<pre><code><span class="hljs-section">server</span> {
    <span class="hljs-comment"># ...</span>
    <span class="hljs-attribute">root</span> __NGINX_ROOT;
    <span class="hljs-comment"># ...</span>

    <span class="hljs-attribute">location</span> <span class="hljs-regexp">~ \.php$</span> {
        <span class="hljs-comment"># ...</span>
        <span class="hljs-attribute">fastcgi_pass</span> php-fpm:<span class="hljs-number">9000</span>;
    }
}
</code></pre><p><code>php-fpm</code> will resolve to the <code>php-fpm</code> container, because we use php-fpm as the service name in the docker-compose file, so it will be <a target="_blank" href="https://docs.docker.com/compose/compose-file/#aliases">automatically used as the hostname</a>:</p>
<blockquote>
<p> Other containers on the same network can use either the service name or [an] alias to connect to one of the service’s containers.</p>
</blockquote>
<p>In the Dockerfile, we use</p>
<pre><code>ARG APP_CODE_PATH
RUN <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>modify_config.sh <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>nginx<span class="hljs-operator">/</span>sites<span class="hljs-operator">-</span>available<span class="hljs-operator">/</span>default.conf \
    <span class="hljs-string">"__NGINX_ROOT"</span> \
    <span class="hljs-string">"${APP_CODE_PATH}"</span> \
;
</code></pre><p><code>APP_CODE_PATH</code> will be passed via docker-compose when we build the container and mounted as a shared directory  from the host system. </p>
<h3 id="heading-workspace-formerly-php-cli"><a id="workspace-formerly-php-cli"></a>workspace (formerly php-cli)</h3>
<p>Click here to <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/workspace/Dockerfile">see the full workspace Dockerfile</a>.</p>
<p>We will use the former <code>php-cli</code> container and make it our <code>workspace</code> as introduced in part 2 of this tutorial under <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#preparing-the-workspace-container">Preparing the "workspace" container</a>.</p>
<p>This will be the container we use to point our IDE to, e.g. to execute tests. Its Dockerfile looks almost identical to the one of the <code>php-fpm</code> service, apart from the SSH setup:</p>
<pre><code># <span class="hljs-keyword">set</span> up ssh
RUN apt-<span class="hljs-keyword">get</span> <span class="hljs-keyword">update</span> -yqq &amp;&amp; apt-<span class="hljs-keyword">get</span> install -yqq openssh-<span class="hljs-keyword">server</span> \
 &amp;&amp; mkdir /var/run/sshd \
;

# <span class="hljs-keyword">add</span> <span class="hljs-keyword">default</span> <span class="hljs-built_in">public</span> key <span class="hljs-keyword">to</span> authorized_keys
<span class="hljs-keyword">USER</span> ${APP_USER}
<span class="hljs-keyword">COPY</span> ${SERVICE_DIR}/.ssh/insecure_id_rsa.pub /tmp/insecure_id_rsa.pub
RUN mkdir -p ~/.ssh \
 &amp;&amp; cat /tmp/insecure_id_rsa.pub &gt;&gt; ~/.ssh/authorized_keys \
 &amp;&amp; chown -R ${APP_USER}: ~/.ssh \
 &amp;&amp; chmod <span class="hljs-number">700</span> ~/.ssh \
 &amp;&amp; chmod <span class="hljs-number">600</span> ~/.ssh/authorized_keys \
;
<span class="hljs-keyword">USER</span> root
</code></pre><h2 id="heading-setting-up-docker-compose"><a id="setting-up-docker-compose"></a>Setting up docker-compose</h2>
<p>In order to orchestrate the build process, we'll use docker-compose.</p>
<h3 id="heading-docker-composeyml"><a id="docker-compose-yml"></a>docker-compose.yml</h3>
<p>See the full  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/docker-compose.yml">docker-compose.yml file in the repository</a></p>
<p>Things to note:</p>
<ul>
<li>each service uses <code>context: .</code> so it has access to the <code>.shared</code> folder.
The context is always <a target="_blank" href="https://docs.docker.com/compose/extends/#understanding-multiple-compose-files">relative to the location of the first docker-compose.yml file</a></li>
<li>all arguments that we used in the Dockerfiles are defined in the <code>args:</code>
section via<pre><code>args:
  <span class="hljs-operator">-</span> APP_CODE_PATH<span class="hljs-operator">=</span>${APP_CODE_PATH_CONTAINER}
  <span class="hljs-operator">-</span> APP_GROUP<span class="hljs-operator">=</span>${APP_GROUP}
  <span class="hljs-operator">-</span> APP_GROUP_ID<span class="hljs-operator">=</span>${APP_GROUP_ID}
  <span class="hljs-operator">-</span> APP_USER<span class="hljs-operator">=</span>${APP_USER}
  <span class="hljs-operator">-</span> APP_USER_ID<span class="hljs-operator">=</span>${APP_USER_ID}
  <span class="hljs-operator">-</span> TZ<span class="hljs-operator">=</span>${TIMEZONE}
</code></pre></li>
<li>the codebase is synced from the host in all containers via<pre><code>volumes:
  - <span class="hljs-variable">${APP_CODE_PATH_HOST}</span>:<span class="hljs-variable">${APP_CODE_PATH_CONTAINER}</span>
</code></pre></li>
<li>the <code>nginx</code> service exposes ports on the host machine so that we can 
access the containers from "outside" via<pre><code>ports:
  - <span class="hljs-string">"<span class="hljs-subst">${NGINX_HOST_HTTP_PORT}</span>:80"</span>
  - <span class="hljs-string">"<span class="hljs-subst">${NGINX_HOST_HTTPS_PORT}</span>:443"</span>
</code></pre></li>
<li>all services are part of the <code>backend</code> network so they can talk to each
other. The <code>nginx</code> service has an additional alias that allows us to
define an arbitrary host name via<pre><code><span class="hljs-attr">networks:</span>
  <span class="hljs-attr">backend:</span>
    <span class="hljs-attr">aliases:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">${APP_HOST}</span>
</code></pre>I prefer to have a dedicated hostname per project (e.g. <code>docker-php-tutorial.local</code>)
instead of using <code>127.0.0.1</code> or <code>localhost</code> directly</li>
</ul>
<h3 id="heading-envexample"><a id="env-example"></a>.env.example</h3>
<p>To fill in all the required variables / arguments, we're using a <code>.env.example</code> file with the following content:</p>
<pre><code><span class="hljs-comment"># Default settings for docker-compose</span>
<span class="hljs-attr">COMPOSE_PROJECT_NAME</span>=docker-php-tutorial
<span class="hljs-attr">COMPOSE_FILE</span>=docker-compose.yml
<span class="hljs-attr">COMPOSE_CONVERT_WINDOWS_PATHS</span>=<span class="hljs-number">1</span>

<span class="hljs-comment"># build</span>
<span class="hljs-attr">PHP_VERSION</span>=<span class="hljs-number">7.3</span>
<span class="hljs-attr">TIMEZONE</span>=UTC
<span class="hljs-attr">NETWORKS_DRIVER</span>=bridge

<span class="hljs-comment"># application</span>
<span class="hljs-attr">APP_USER</span>=www-data
<span class="hljs-attr">APP_GROUP</span>=www-data
<span class="hljs-attr">APP_USER_ID</span>=<span class="hljs-number">1000</span>
<span class="hljs-attr">APP_GROUP_ID</span>=<span class="hljs-number">1000</span>
<span class="hljs-attr">APP_CODE_PATH_HOST</span>=../
<span class="hljs-attr">APP_CODE_PATH_CONTAINER</span>=/var/www/current

<span class="hljs-comment"># required so we can reach the nginx server from other containers via that hostname</span>
<span class="hljs-attr">APP_HOST</span>=docker-php-tutorial.local

<span class="hljs-comment"># nginx</span>
<span class="hljs-attr">NGINX_HOST_HTTP_PORT</span>=<span class="hljs-number">80</span>
<span class="hljs-attr">NGINX_HOST_HTTPS_PORT</span>=<span class="hljs-number">443</span>

<span class="hljs-comment"># workspace</span>
<span class="hljs-attr">WORKSPACE_HOST_SSH_PORT</span>=<span class="hljs-number">2222</span>
</code></pre><p>The <code>COMPOSE_</code> variables in the beginning set some reasonable  <a target="_blank" href="https://docs.docker.com/compose/reference/envvars/#compose_file">defaults for docker-compose</a>.</p>
<p>###<a id="building-and-running-the-containers"></a>Building and running the containers</p>
<p>By now, we should have everything we need set up to get our dockerized PHP development up and running. If you haven't done it already, now would be a great time to clone  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">the repository</a> and checkout the  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects"><code>part_3_structuring-the-docker-setup-for-php-projects</code> branch</a>:</p>
<pre><code>git clone https:<span class="hljs-comment">//github.com/paslandau/docker-php-tutorial.git</span>
cd docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial
git checkout part_3_structuring<span class="hljs-operator">-</span>the<span class="hljs-operator">-</span>docker<span class="hljs-operator">-</span>setup<span class="hljs-operator">-</span><span class="hljs-keyword">for</span><span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>projects
</code></pre><p>Now copy the <code>.env.exmaple</code> to <code>.env</code>. All the default values  should work out of the box - unless you already have something running on port <code>80</code> or <code>443</code>. In that case you have to change <code>NGINX_HOST_HTTP_PORT / NGINX_HOST_HTTP_PORT</code> to a free port. </p>
<pre><code><span class="hljs-selector-tag">cp</span> <span class="hljs-selector-class">.env</span><span class="hljs-selector-class">.example</span> <span class="hljs-selector-class">.env</span>
</code></pre><p>We can examine the "final" docker-compose.yml <strong>after</strong> the variable substitution via</p>
<pre><code>docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>f .docker/docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span><span class="hljs-operator">-</span>project<span class="hljs-operator">-</span>directory .docker config
</code></pre><pre><code>networks:
  backend:
    driver: bridge
services:
  nginx:
    build:
      args:
        APP_CODE_PATH: <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>www<span class="hljs-operator">/</span>current
        APP_GROUP: www<span class="hljs-operator">-</span>data
        APP_GROUP_ID: <span class="hljs-string">'1000'</span>
        APP_USER: www<span class="hljs-operator">-</span>data
        APP_USER_ID: <span class="hljs-string">'1000'</span>
        TZ: UTC
      context: D:\codebase\docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial\.docker
      dockerfile: ./nginx<span class="hljs-operator">/</span>Dockerfile
    image: php<span class="hljs-operator">-</span>docker<span class="hljs-operator">-</span>tutorial<span class="hljs-operator">/</span>nginx
    networks:
      backend:
        aliases:
        <span class="hljs-operator">-</span> docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial.local
    ports:
    <span class="hljs-operator">-</span> published: <span class="hljs-number">80</span>
      target: <span class="hljs-number">80</span>
    <span class="hljs-operator">-</span> published: <span class="hljs-number">443</span>
      target: <span class="hljs-number">443</span>
    volumes:
    <span class="hljs-operator">-</span> <span class="hljs-operator">/</span>d<span class="hljs-operator">/</span>codebase<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>www<span class="hljs-operator">/</span>current:rw
  php<span class="hljs-operator">-</span>fpm:
<span class="hljs-comment">// ...</span>
</code></pre><p>Note, that this command is run from <code>./docker-php-tutorial</code>. If we would run this from <code>./docker-php-tutorial/.docker</code>, we could simply use <code>docker-compose config</code> - but since we'll define that in a Makefile later anyway, the additional "verbosity" won't matter ;)</p>
<p>This command is also a great way to check the various paths that are resolved to their absolute form, e.g.  </p>
<pre><code><span class="hljs-attribute">context</span>: <span class="hljs-attribute">D</span>:\codebase\docker-php-tutorial\.docker
</code></pre><p>and </p>
<pre><code>volumes:
<span class="hljs-operator">-</span> <span class="hljs-operator">/</span>d<span class="hljs-operator">/</span>codebase<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>www<span class="hljs-operator">/</span>current:rw
</code></pre><p>The actual build is triggered via </p>
<pre><code>docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>f .docker/docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span><span class="hljs-operator">-</span>project<span class="hljs-operator">-</span>directory .docker build <span class="hljs-operator">-</span><span class="hljs-operator">-</span>parallel
</code></pre><p>Since we have more than one container, it makes sense to build with  <a target="_blank" href="https://docs.docker.com/compose/reference/build/"><code>--parallel</code></a>.</p>
<p>To start the containers, we use </p>
<pre><code>docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>f .docker/docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span><span class="hljs-operator">-</span>project<span class="hljs-operator">-</span>directory .docker up <span class="hljs-operator">-</span>d
</code></pre><p>and should see   </p>
<pre><code>$ docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>f .docker/docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span><span class="hljs-operator">-</span>project<span class="hljs-operator">-</span>directory .docker up <span class="hljs-operator">-</span>d
Starting docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial_nginx_1     ... done
Starting docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial_workspace_1 ... done
Starting docker<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>tutorial_php<span class="hljs-operator">-</span>fpm_1   ... done
</code></pre><h3 id="heading-testing"><a id="testing-if-everything-works"></a>Testing</h3>
<p>if everything works After rewriting our own docker setup a couple of times, I've come to appreciate a structured way to test if  "everything" works. Everything as in:</p>
<ul>
<li>are all containers running?</li>
<li>does "host.docker.internal" exist?</li>
<li>do we see the correct output when sending a request to nginx/php-fpm?</li>
<li>are all required php extensions installed?</li>
</ul>
<p>This might seem superfluous (after all, we just defined excatly that in the Dockerfiles), but there will come a time when you (or someone else) need to make changes (new PHP version, new extensions, etc.) and having something that runs automatically and informs you about obvious flaws is a real time saver. </p>
<p>You can see  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/.docker/docker-test.sh">the full test file in the repository</a>.  Since my bash isn't the best, I try to keep it as simple as possible. The tests can be run via</p>
<pre><code>sh .docker/docker<span class="hljs-operator">-</span>test.sh
</code></pre><p>and should yield something like this: </p>
<pre><code>Testing service <span class="hljs-string">'workspace'</span>
<span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span>
Checking <span class="hljs-keyword">if</span> <span class="hljs-string">'workspace'</span> has a running container
OK
Testing PHP version <span class="hljs-string">'7.3'</span> on <span class="hljs-string">'workspace'</span> <span class="hljs-keyword">for</span> <span class="hljs-string">'php'</span> and expect to see <span class="hljs-string">'PHP 7.3'</span>
OK
Testing PHP module <span class="hljs-string">'xdebug'</span> on <span class="hljs-string">'workspace'</span> <span class="hljs-keyword">for</span> <span class="hljs-string">'php'</span>
OK
Testing PHP module <span class="hljs-string">'Zend OPcache'</span> on <span class="hljs-string">'workspace'</span> <span class="hljs-keyword">for</span> <span class="hljs-string">'php'</span>
OK
Checking <span class="hljs-string">'host.docker.internal'</span> on <span class="hljs-string">'workspace'</span>
OK

Testing service <span class="hljs-string">'php-fpm'</span>
<span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span>
...
</code></pre><h2 id="heading-makefile-and-bashrc"><a id="makefile-and-bashrc"></a>Makefile and <code>.bashrc</code></h2>
<p>In the previous sections I have introduced a couple of commands, e.g. for building and running containers. And to be honest, I find it kinda challenging to keep them in mind without having to look up the exact options and arguments. I would usually create a helper function or an alias in my local <code>.bashrc</code> file in a situation like that - but that wouldn't be available to other members of the team then and it would be very specific to this one project.  Instead we'll provide a <code>Makefile</code> as a central reference point.</p>
<h3 id="heading-using-make-as-central-entry-point"><a id="using-make-as-central-entry-point"></a>Using <code>make</code> as central entry point</h3>
<p>Please refer <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/blob/part_3_structuring-the-docker-setup-for-php-projects/Makefile">to the repository for the full <code>Makefile</code></a>.</p>
<p>Going into the details of <code>make</code> is a little out of scope for this article,  so I kindly refer to some articles that helped me get started:</p>
<ul>
<li><a target="_blank" href="https://localheinz.com/blog/2018/01/24/makefile-for-lazy-developers/">Makefile for lazy developers</a></li>
<li><a target="_blank" href="https://blog.theodo.fr/2018/05/why-you-need-a-makefile-on-your-project/">Why you Need a Makefile on your Project</a></li>
</ul>
<p>Both are written with a PHP context in mind.  Tip: If you are using PhpStorm, give the <a target="_blank" href="https://plugins.jetbrains.com/plugin/9333-makefile-support">Makefile support plugin</a> a try. And don't forget the number one rule:  <a target="_blank" href="https://stackoverflow.com/q/14109724">A <code>Makefile</code> requires tabs</a>!</p>
<p>Note: If you are using Windows, <code>make</code> is probably not available. See  <a class="post-section-overview" href="#install-make-on-windows-mingw">Install make on Windows (MinGW)</a> for instructions to set it up.</p>
<p>The <code>Makefile</code> ist located in the root of the application. Since we use a <code>help</code> target that makes the  <a target="_blank" href="https://suva.sh/posts/well-documented-makefiles/"><code>Makefile</code> self-documenting</a>, we can simply run <code>make</code> to see all the available commands:</p>
<pre><code>$ make

Usage:
  make <span class="hljs-operator">&lt;</span>target<span class="hljs-operator">&gt;</span>

[Docker] Build <span class="hljs-operator">/</span> Infrastructure
  docker<span class="hljs-operator">-</span>clean                 Remove the .env file <span class="hljs-keyword">for</span> docker
  docker<span class="hljs-operator">-</span>init                  Make sure the .env file exists <span class="hljs-keyword">for</span> docker
  docker<span class="hljs-operator">-</span>build<span class="hljs-operator">-</span><span class="hljs-keyword">from</span><span class="hljs-operator">-</span>scratch    Build all docker images <span class="hljs-keyword">from</span> scratch, without cache etc. Build a specific image by providing the service name via: make docker<span class="hljs-operator">-</span>build CONTAINER<span class="hljs-operator">=</span><span class="hljs-operator">&lt;</span>service<span class="hljs-operator">&gt;</span>
  docker<span class="hljs-operator">-</span>build                 Build all docker images. Build a specific image by providing the service name via: make docker<span class="hljs-operator">-</span>build CONTAINER<span class="hljs-operator">=</span><span class="hljs-operator">&lt;</span>service<span class="hljs-operator">&gt;</span>
  docker<span class="hljs-operator">-</span>up                    Start all docker containers. To only start one container, use CONTAINER<span class="hljs-operator">=</span><span class="hljs-operator">&lt;</span>service<span class="hljs-operator">&gt;</span>
  docker<span class="hljs-operator">-</span>down                  Stop all docker containers. To only stop one container, use CONTAINER<span class="hljs-operator">=</span><span class="hljs-operator">&lt;</span>service<span class="hljs-operator">&gt;</span>
  docker<span class="hljs-operator">-</span>test                  Run the infrastructure tests <span class="hljs-keyword">for</span> the docker setup
</code></pre><p>As a new developer, your "onboarding" to get a running infrastructure should now look like this:</p>
<pre><code>make docker<span class="hljs-operator">-</span>clean
make docker<span class="hljs-operator">-</span>init
make docker<span class="hljs-operator">-</span>build<span class="hljs-operator">-</span><span class="hljs-keyword">from</span><span class="hljs-operator">-</span>scratch
make docker<span class="hljs-operator">-</span>test
</code></pre><h3 id="heading-install-make-on-windows-mingw"><a id="install-make-on-windows-mingw"></a>Install make on Windows (MinGW)</h3>
<p><code>make</code> doesn't exist on Windows and is also not part of the standard installation of MinGW  (click here <a target="_blank" href="https://www.pascallandau.com/blog/phpstorm-with-vagrant-using-laravel-homestead-on-windows-10/#git-and-git-bash">to learn how to setup MinGW</a>) Setting is up is straight forward but as with "everything UI" it's easier if you can  actually "see what I'm doing" - so here's a video:</p>
<p>{% youtube taCJhnBXG_w %}</p>
<p>The steps are as follows:</p>
<ul>
<li>Set up <code>mingw-get</code><ul>
<li>Instructions: https://web.archive.org/web/20200226035236/http://www.mingw.org/wiki/getting_started#toc5</li>
<li>Download: https://sourceforge.net/projects/mingw/files/Installer/mingw-get-setup.exe/download</li>
<li>Install and <a target="_blank" href="https://www.pascallandau.com/blog/php7-with-xdebug-2-4-for-phpstorm-on-windows-10/#the-path-variable">add the <code>bin/</code> directory to <code>PATH</code> (shortcut <code>systempropertiesadvanced</code>)</a>.
Notes: <ul>
<li>Do not use an installation path that contains spaces!</li>
<li>The installation path can be different from your MinGW location</li>
</ul>
</li>
</ul>
</li>
<li>Install <code>mingw32-make</code> via<pre><code>mingw<span class="hljs-operator">-</span>get install mingw32<span class="hljs-operator">-</span>make
</code></pre><ul>
<li>create the file <code>bin/make</code> with the content<pre><code>mingw32<span class="hljs-operator">-</span>make.exe $<span class="hljs-operator">*</span>
</code></pre></li>
<li>Note: Sometimes Windows won't recognize non-.exe files - so instead of <code>bin/make</code> you might need to name the file
<code>bin/make.exe</code> (with the same content)</li>
</ul>
</li>
<li>Open a new shell and type <code>make</code>. The output should look something like this<pre><code>$ make
mingw32<span class="hljs-operator">-</span>make: <span class="hljs-operator">*</span><span class="hljs-operator">*</span><span class="hljs-operator">*</span> Keine Targets angegeben und keine ¦make¦<span class="hljs-operator">-</span>Steuerdatei gefunden.  Schluss.
</code></pre></li>
</ul>
<h3 id="heading-easy-container-access-via-din-bashrc-helper"><a id="easy-container-access-via-din-bashrc-helper"></a>Easy container access via <code>din</code> .bashrc helper</h3>
<p>I've got one last goodie for working with Docker that I use all the time: </p>
<p>Logging into a running container via <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/exec/#run-docker-exec-on-a-running-container"><code>docker exec</code></a> and the <code>din / dshell</code> helper.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/easy-docker-login-din.gif.png"><img src="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/easy-docker-login-din.gif" alt="Log into any running docker container via din helper" /></a></p>
<p>To make this work, put the following code in your <code>.bashrc</code> file </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">din</span>(<span class="hljs-params"></span>) </span>{
  filter<span class="hljs-operator">=</span>$1

  user<span class="hljs-operator">=</span><span class="hljs-string">""</span>
  <span class="hljs-keyword">if</span> [[ <span class="hljs-operator">-</span>n <span class="hljs-string">"$2"</span> ]];
  then
      user<span class="hljs-operator">=</span><span class="hljs-string">"--user $2"</span>
  fi

  shell<span class="hljs-operator">=</span><span class="hljs-string">"bash"</span>
  <span class="hljs-keyword">if</span> [[ <span class="hljs-operator">-</span>n <span class="hljs-string">"$3"</span> ]];
  then
      shell<span class="hljs-operator">=</span>$3
  fi

  prefix<span class="hljs-operator">=</span><span class="hljs-string">""</span>
  <span class="hljs-keyword">if</span> [[ <span class="hljs-string">"$(expr substr $(uname -s) 1 5)"</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"MINGW"</span> ]]; then
      prefix<span class="hljs-operator">=</span><span class="hljs-string">"winpty"</span>
  fi
  ${prefix} docker exec <span class="hljs-operator">-</span>it ${user} $(docker ps <span class="hljs-operator">-</span><span class="hljs-operator">-</span>filter name<span class="hljs-operator">=</span>${filter} <span class="hljs-operator">-</span>q <span class="hljs-operator">|</span> head <span class="hljs-number">-1</span>) ${shell}
}
</code></pre><p>The <code>$(docker ps --filter name=${filter} -q | head -1)</code> part will find partial matches on running containers  for the first argument and pass the result to the <code>docker exec</code> command. In effect, we can log into any container  by only providing a minimal matching string on the container name. E.g. to log in the <code>workspace</code> container I can now simply type <code>din works</code> from <em>anywhere</em> on my system.</p>
<h2 id="heading-fundamentals-on-building-the-containers"><a id="fundamentals-on-building-the-containers"></a>Fundamentals on building the containers</h2>
<p>Since we have now "seen" the end result, let's take a closer look behind the scenes.  I assume that you are already somewhat familiar with <code>Dockerfile</code>s and have used <code>docker-compose</code> to orchestrate multiple  services (if not, check out  <a target="_blank" href="blog/php-php-fpm-and-nginx-on-docker-in-windows-10/#dockerfile">Persisting image changes with a Dockerfile</a> and <a target="_blank" href="blog/php-php-fpm-and-nginx-on-docker-in-windows-10/#docker-compose">Putting it all together: Meet docker-compose</a>). But there are some points I would like to cover in a little more detail.</p>
<h3 id="heading-understanding-build-context"><a id="understanding-build-context"></a>Understanding build context</h3>
<p>There are two essential parts when building a container:</p>
<ul>
<li>the Dockerfile</li>
<li>the build context</li>
</ul>
<p>You can read about the official description in the <a target="_blank" href="http://docs.docker.com/engine/reference/builder/#usage">Dockerfile reference</a>. You'll usually see something like this:</p>
<pre><code><span class="hljs-attribute">docker</span> build .
</code></pre><p>which assumes that you use the current directory as build context and that there is a Dockerfile in the same directory.</p>
<p>But you can also start the build via</p>
<pre><code>docker build .docker <span class="hljs-operator">-</span>f .docker/nginx<span class="hljs-operator">/</span>Dockerfile
                 <span class="hljs-operator">|</span>      <span class="hljs-operator">|</span>
                 <span class="hljs-operator">|</span>      └── use the Dockerfile at <span class="hljs-string">".docker/nginx/Dockerfile"</span>
                 <span class="hljs-operator">|</span>
                 └── use the .docker subdirectory <span class="hljs-keyword">as</span> build context
</code></pre><p>For me, the gist is this: The build context defines the files and folders (recursively) on your machine that are send  from the <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/cli/">Docker CLI</a> to  the <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/dockerd/">Docker Daemon</a> that executes the build process of a container so that you can reference those files in the Dockerfile (e.g. via <code>COPY</code>). Take the following structure for example:</p>
<pre><code><span class="hljs-operator">&lt;</span>project<span class="hljs-operator">&gt;</span><span class="hljs-operator">/</span>
├── .docker/
    ├── .shared/
    <span class="hljs-operator">|</span>   └── scripts<span class="hljs-operator">/</span>
    <span class="hljs-operator">|</span>       └── ...
    └── nginx<span class="hljs-operator">/</span>
        ├── nginx.conf
        └── Dockerfile
</code></pre><p>Assume, that the current working directory is <code>&lt;project&gt;/</code>. If we started a build via </p>
<pre><code>docker build .docker/nginx <span class="hljs-operator">-</span>f .docker/nginx<span class="hljs-operator">/</span>Dockerfile
</code></pre><p>the context would <strong>not</strong> include the <code>.shared</code> folder so we wouldn't be able to <code>COPY</code> the <code>scripts/</code> subfolder.  If we ran</p>
<pre><code>docker build .docker <span class="hljs-operator">-</span>f .docker/nginx<span class="hljs-operator">/</span>Dockerfile
</code></pre><p>however, that would make the <code>.shared</code> folder available. In the Dockerfile itself, I need to know what the build context is, because I need to adjust the paths accordingly. Concrete example for the folder structure above and build  triggered via <code>docker build .docker -f .docker/nginx/Dockerfile</code>:</p>
<pre><code><span class="hljs-keyword">FROM</span>:nginx

<span class="hljs-comment"># build context is .docker ...</span>

<span class="hljs-comment"># ... so the following COPY refers to .docker/.shared</span>
COPY ./.shared /tmp

<span class="hljs-comment"># ... so the following COPY refers to .docker/nginx/nginx.conf</span>
COPY ./nginx/nginx.conf /tmp
</code></pre><p>The build context for all of our containers will be the <code>.docker</code> directory,  so that all build processes have access to the <code>.shared</code> scripts and config.  Yes, that also means that the <code>php-fpm</code> container has access to files that are only relevant to the <code>mysql</code> container (for instance), but the performance penalty is absolutely neglectable. Plus, as long as we don't actively <code>COPY</code> those irrelevant files, they won't bloat up our images.</p>
<p>A couple of notes:</p>
<ul>
<li>I used to think that the build context is <em>always</em> tied to the location of the Dockerfile but that's only the default,
it can be any directory</li>
<li>the build context is <strong>actually send</strong> to the build process - i.e. you should avoid unnecessary files / folders as this might
affect performance, especially on big files (iaw: don't use <code>/</code> as context!)</li>
<li>similar to <code>git</code>, Docker knows the concept of a <a target="_blank" href="https://docs.docker.com/engine/reference/builder/#dockerignore-file"><code>.dockerignore</code> file</a>
to exclude files from being included in the build context</li>
</ul>
<h3 id="heading-dockerfile-template"><a id="dockerfile-template"></a>Dockerfile template</h3>
<p>The Dockerfiles for the containers roughly follow the structure outlined below:</p>
<pre><code><span class="hljs-attribute">FROM</span> ...

<span class="hljs-comment"># path to the directory where the Dockerfile lives relative to the build context</span>
ARG SERVICE_DIR=<span class="hljs-string">"./service"</span>

<span class="hljs-comment"># get the scripts from the build context and make sure they are executable</span>
COPY .shared/scripts/ /tmp/scripts/
RUN chmod +x -R /tmp/scripts/

<span class="hljs-comment"># set timezone</span>
ARG TZ=UTC
RUN /tmp/scripts/set_timezone.sh <span class="hljs-variable">${TZ}</span>

<span class="hljs-comment"># add users</span>
ARG APP_USER=www-data
ARG APP_USER_ID=<span class="hljs-number">1000</span>
ARG APP_GROUP=$(APP_USER)
ARG APP_GROUP_ID=$(APP_USER_ID)

RUN /tmp/scripts/create_user.sh <span class="hljs-variable">${APP_USER}</span> <span class="hljs-variable">${APP_GROUP}</span> <span class="hljs-variable">${APP_USER_ID}</span> <span class="hljs-variable">${APP_GROUP_ID}</span>

<span class="hljs-comment"># install common software</span>
RUN /tmp/scripts/install_software.sh

<span class="hljs-comment"># perform any other, container specific build steps</span>
COPY <span class="hljs-variable">${SERVICE_DIR}</span>/config/* /etc/service/config
RUN /tmp/scripts/modify_config.sh /etc/service/config/default.conf \
    <span class="hljs-string">"__APP_USER"</span> \
    <span class="hljs-string">"<span class="hljs-variable">${APP_USER}</span>"</span> \
;
<span class="hljs-comment"># [...]</span>

<span class="hljs-comment"># set default work directory</span>
<span class="hljs-attribute">WORKDIR</span> <span class="hljs-string">"..."</span>

<span class="hljs-comment"># cleanup </span>
RUN /tmp/scripts/cleanup.sh

<span class="hljs-comment"># define ENTRYPOINT</span>
ENTRYPOINT [...]
CMD [...]
</code></pre><p>The comments should suffice to give you an overview - so let's talk about the individual parts in detail.</p>
<h3 id="heading-setting-the-timezone"><a id="setting-the-timezone"></a>Setting the timezone</h3>
<p><strong>Script: <code>set_timezone.sh</code></strong></p>
<p>Let's start with a simple and obvious one: Ensuring that all containers use the same system timezone (see <a target="_blank" href="https://www.itzgeek.com/how-tos/linux/debian/how-to-change-timezone-in-debian-9-8-ubuntu-16-04-14-04-linuxmint-18.html">here</a> and <a target="_blank" href="https://unix.stackexchange.com/q/452559">here</a>)</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

TZ=<span class="hljs-variable">$1</span>
ln -snf /usr/share/zoneinfo/<span class="hljs-variable">$TZ</span> /etc/localtime &amp;&amp; <span class="hljs-built_in">echo</span> <span class="hljs-variable">$TZ</span> &gt; /etc/timezone
</code></pre><p>The script is then called from the <code>Dockerfile</code> via </p>
<pre><code>ARG TZ<span class="hljs-operator">=</span>UTC
RUN <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>set_timezone.sh ${TZ}
</code></pre><h3 id="heading-synchronizing-file-and-folder-ownership-on-shared-volumes"><a id="synchronizing-file-and-folder-ownership-on-shared-volumes"></a>Synchronizing file and folder ownership on shared volumes</h3>
<p><strong>Script: <code>create_user.sh</code></strong></p>
<p>Docker makes it really easy to share files between containers by using <a target="_blank" href="https://docs.docker.com/storage/volumes/">volumes</a>.  For simplicities sake, you can picture a volume simply as an additional disk that multiple containers have access to. And since it's PHP we're talking about here, sharing the same application files is a common requirement  (e.g. for <code>php-fpm</code>, <code>nginx</code>, <code>php-workers</code>).</p>
<p>As long as you are only dealing with one container, life is easy: You can simply <code>chown</code> files to the correct user. But since the containers might have a different user setup, permissions/ownership becomes a problem. Checkout  <a target="_blank" href="https://serversforhackers.com/c/dckr-file-permissions">this video on Docker &amp; File Permissions</a> for a practical  example in a Laravel application.</p>
<p>The first thing for me was understanding that file ownership does not depend on the user <strong>name</strong> but rather on the user <strong>id</strong>.  And you might have guessed it: Two containers might have a user with the same name but with a different id.  The same is true for groups, btw. You can check the id by running <code>id &lt;name&gt;</code>, e.g.</p>
<pre><code>id www<span class="hljs-operator">-</span>data
uid<span class="hljs-operator">=</span><span class="hljs-number">33</span>(www<span class="hljs-operator">-</span>data) gid<span class="hljs-operator">=</span><span class="hljs-number">33</span>(www<span class="hljs-operator">-</span>data) groups<span class="hljs-operator">=</span><span class="hljs-number">33</span>(www<span class="hljs-operator">-</span>data)
</code></pre><p><a target="_blank" href="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/docker-file-ownership-volume.png"><img src="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/docker-file-ownership-volume.png" alt="File ownership with multiple containers using a shared volume" /></a></p>
<p>That's inconvenient but rather easy to solve in most cases, because we have full control over the containers and can <a target="_blank" href="https://www.cyberciti.biz/faq/linux-change-user-group-uid-gid-for-all-owned-files/">assign ids as we like</a>  (using <code>usermod -u &lt;id&gt; &lt;name&gt;</code>) and thus making sure every container uses the same user names with the same user ids.</p>
<p>Things get complicated when the volume isn't just a Docker volume but a shared folder on the host. This is usually what we want for development, so that changes on the host are immediately reflected in all the containers.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/docker-file-ownership-host.png"><img src="https://www.pascallandau.com/img/structuring-the-docker-setup-for-php-projects/docker-file-ownership-host.png" alt="File ownership with multiple containers using a shared volume from the host" /></a></p>
<p>This issue <strong>only affects users with a linux host system</strong>! Docker Desktop (previously known as Docker for Mac / Docker for Win) has a virtualization layer in between that will effectively erase all ownership settings and make everything shared from the host available to every user in a container.</p>
<p>We use the following script to ensure a consistent user setup when building a container:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

APP_USER=<span class="hljs-variable">$1</span>
APP_GROUP=<span class="hljs-variable">$2</span>
APP_USER_ID=<span class="hljs-variable">$3</span>
APP_GROUP_ID=<span class="hljs-variable">$4</span>

new_user_id_exists=$(id <span class="hljs-variable">${APP_USER_ID}</span> &gt; /dev/null 2&gt;&amp;1; <span class="hljs-built_in">echo</span> $?) 
<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$new_user_id_exists</span>"</span> = <span class="hljs-string">"0"</span> ]; <span class="hljs-keyword">then</span>
    (&gt;&amp;2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"ERROR: APP_USER_ID <span class="hljs-variable">$APP_USER_ID</span> already exists - Aborting!"</span>);
    <span class="hljs-built_in">exit</span> 1;
<span class="hljs-keyword">fi</span>

new_group_id_exists=$(getent group <span class="hljs-variable">${APP_GROUP_ID}</span> &gt; /dev/null 2&gt;&amp;1; <span class="hljs-built_in">echo</span> $?) 
<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$new_group_id_exists</span>"</span> = <span class="hljs-string">"0"</span> ]; <span class="hljs-keyword">then</span>
    (&gt;&amp;2 <span class="hljs-built_in">echo</span> <span class="hljs-string">"ERROR: APP_GROUP_ID <span class="hljs-variable">$APP_GROUP_ID</span> already exists - Aborting!"</span>);
    <span class="hljs-built_in">exit</span> 1;
<span class="hljs-keyword">fi</span>

old_user_id=$(id -u <span class="hljs-variable">${APP_USER}</span>)
old_user_exists=$(id -u <span class="hljs-variable">${APP_USER}</span> &gt; /dev/null 2&gt;&amp;1; <span class="hljs-built_in">echo</span> $?) 
old_group_id=$(getent group <span class="hljs-variable">${APP_GROUP}</span> | cut -d: -f3)
old_group_exists=$(getent group <span class="hljs-variable">${APP_GROUP}</span> &gt; /dev/null 2&gt;&amp;1; <span class="hljs-built_in">echo</span> $?)

<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$old_group_id</span>"</span> != <span class="hljs-string">"<span class="hljs-variable">${APP_GROUP_ID}</span>"</span> ]; <span class="hljs-keyword">then</span>
    <span class="hljs-comment"># create the group</span>
    groupadd -f <span class="hljs-variable">${APP_GROUP}</span>
    <span class="hljs-comment"># and the correct id</span>
    groupmod -g <span class="hljs-variable">${APP_GROUP_ID}</span> <span class="hljs-variable">${APP_GROUP}</span>
    <span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$old_group_exists</span>"</span> = <span class="hljs-string">"0"</span> ]; <span class="hljs-keyword">then</span>
        <span class="hljs-comment"># set the permissions of all "old" files and folder to the new group</span>
        find / -group <span class="hljs-variable">$old_group_id</span> -<span class="hljs-built_in">exec</span> chgrp -h <span class="hljs-variable">${APP_GROUP}</span> {} \; || <span class="hljs-literal">true</span>
    <span class="hljs-keyword">fi</span> 
<span class="hljs-keyword">fi</span>

<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$old_user_id</span>"</span> != <span class="hljs-string">"<span class="hljs-variable">${APP_USER_ID}</span>"</span> ]; <span class="hljs-keyword">then</span>
    <span class="hljs-comment"># create the user if it does not exist</span>
    <span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$old_user_exists</span>"</span> != <span class="hljs-string">"0"</span> ]; <span class="hljs-keyword">then</span>
        useradd <span class="hljs-variable">${APP_USER}</span> -g <span class="hljs-variable">${APP_GROUP}</span>
    <span class="hljs-keyword">fi</span>

    <span class="hljs-comment"># make sure the home directory exists with the correct permissions</span>
    mkdir -p /home/<span class="hljs-variable">${APP_USER}</span> &amp;&amp; chmod 755 /home/<span class="hljs-variable">${APP_USER}</span> &amp;&amp; chown <span class="hljs-variable">${APP_USER}</span>:<span class="hljs-variable">${APP_GROUP}</span> /home/<span class="hljs-variable">${APP_USER}</span> 

    <span class="hljs-comment"># change the user id, set the home directory and make sure the user has a login shell</span>
    usermod -u <span class="hljs-variable">${APP_USER_ID}</span> -m -d /home/<span class="hljs-variable">${APP_USER}</span> <span class="hljs-variable">${APP_USER}</span> -s $(<span class="hljs-built_in">which</span> bash)

    <span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$old_user_exists</span>"</span> = <span class="hljs-string">"0"</span> ]; <span class="hljs-keyword">then</span>
        <span class="hljs-comment"># set the permissions of all "old" files and folder to the new user </span>
        find / -user <span class="hljs-variable">$old_user_id</span> -<span class="hljs-built_in">exec</span> chown -h <span class="hljs-variable">${APP_USER}</span> {} \; || <span class="hljs-literal">true</span>
    <span class="hljs-keyword">fi</span>
<span class="hljs-keyword">fi</span>
</code></pre><p>The script is then called from the <code>Dockerfile</code> via </p>
<pre><code>ARG APP_USER<span class="hljs-operator">=</span>www<span class="hljs-operator">-</span>data
ARG APP_USER_ID<span class="hljs-operator">=</span><span class="hljs-number">1000</span>
ARG APP_GROUP<span class="hljs-operator">=</span>$(APP_USER)
ARG APP_GROUP_ID<span class="hljs-operator">=</span>$(APP_USER_ID)

RUN <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>create_user.sh ${APP_USER} ${APP_GROUP} ${APP_USER_ID} ${APP_GROUP_ID}
</code></pre><p>The default values can be overridden by passing in the corresponding  <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg">build args</a>. </p>
<p>Linux users should use the user id of the user on their host system - for Docker Desktop users the defaults are fine.</p>
<h3 id="heading-modifying-configuration-files"><a id="modifying-configuration-files"></a>Modifying configuration files</h3>
<p>For most services we probably need some custom configuration settings, like</p>
<ul>
<li>setting php.ini values</li>
<li>changing the default user of a service </li>
<li>changing the location of logfiles</li>
</ul>
<p>There are a couple of   <a target="_blank" href="https://dantehranian.wordpress.com/2015/03/25/how-should-i-get-application-configuration-into-my-docker-containers/">common approaches to modify application configuration in docker</a> and we are currently trying to stick to two rules: 1. provide additional files that override defaults if possible 2. change non-static values with a simple search and replace via <code>sed</code> during the container build</p>
<h4 id="heading-providing-additional-config-files"><a id="providing-additional-config-files"></a>Providing additional config files</h4>
<p>Most services allow the specification of additional configuration files that override the default values in  a default config file. This is great because we only need to define the settings that we actually care about  instead of copying a full file with lots of redundant values.</p>
<p>Take the <a target="_blank" href="http://php.net/manual/en/configuration.file.php#configuration.file.scan"><code>php.ini</code> file</a> for example: It allows to places additional <code>.ini</code> files in a specific directory that override the default values. An easy way to find this directory is <code>php -i | grep "additional .ini"</code>:</p>
<pre><code>$ php <span class="hljs-operator">-</span>i <span class="hljs-operator">|</span> grep <span class="hljs-string">"additional .ini"</span>
Scan <span class="hljs-built_in">this</span> dir <span class="hljs-keyword">for</span> additional .ini files <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> <span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>local<span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>php<span class="hljs-operator">/</span>conf.d
</code></pre><p>So instead of providing a "full" <code>php.ini</code> file, we will use a <code>zz-app.ini</code> file instead, that <strong>only</strong> contains the .ini settings we actually want to change and place it under <code>/usr/local/etc/php/conf.d</code>. </p>
<p>Why <code>zz-</code>? Because</p>
<blockquote>
<p>[...] Within each directory, PHP will scan all files ending in .ini in alphabetical order.</p>
</blockquote>
<p>so if we want to ensure that our .ini files comes last (overriding all previous settings), we'll give it a corresponding prefix :)</p>
<p>The full process would look like this:</p>
<ul>
<li>place the file in the <code>.docker</code> folder, e.g. at <code>.docker/.shared/config/php/conf.d/zz-app.ini</code></li>
<li>pass the folder as build context</li>
<li>in the Dockerfile, use <code>COPY .shared/config/php/conf.d/zz-app.ini /usr/local/etc/php/conf.d/zz-app.ini</code></li>
</ul>
<h4 id="heading-changing-non-static-values"><a id="changing-non-static-values"></a>Changing non-static values</h4>
<p><strong>Script: <code>modify_config.sh</code></strong></p>
<p>Some configuration values are subject to local settings and thus should not be hard coded in configuration files.  Take the <code>memory_limit</code> configuration for <code>php-fpm</code> as an example: Maybe someone in the team can only dedicate a limited amount of memory to docker, so the <code>memory_limit</code> has to be kept lower than usual.</p>
<p>We'll account for that fact by using a variable prefixed by <code>__</code> instead of the real value and replace it with a dynamic argument in the Dockerfile. Example for the aforementioned <code>zz-app.ini</code>:</p>
<pre><code><span class="hljs-attr">memory_limit</span> = __MEMORY_LIMIT
</code></pre><p>We use the following script <code>modify_config.sh</code> to replace the value:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

CONFIG_FILE=<span class="hljs-variable">$1</span>
VAR_NAME=<span class="hljs-variable">$2</span>
VAR_VALUE=<span class="hljs-variable">$3</span>

sed -i -e <span class="hljs-string">"s#<span class="hljs-variable">${VAR_NAME}</span>#<span class="hljs-variable">${VAR_VALUE}</span>#"</span> <span class="hljs-string">"<span class="hljs-variable">${CONFIG_FILE}</span>"</span>
</code></pre><p>The script is then called from the <code>Dockerfile</code> via </p>
<pre><code>ARG PHP_FPM_MEMORY_LIMIT<span class="hljs-operator">=</span>1024M

RUN <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>modify_config.sh \
    <span class="hljs-string">"/usr/local/etc/php/conf.d/zz-app.ini"</span> \
    <span class="hljs-string">"__MEMORY_LIMIT"</span> \
    <span class="hljs-string">"${PHP_FPM_MEMORY_LIMIT}"</span> \
;
</code></pre><p>where <code>PHP_FPM_MEMORY_LIMIT</code> has a default value of <code>1024M</code> but can be overridden when the actual build is initiated.</p>
<h3 id="heading-installing-php-extensions"><a id="installing-php-extensions"></a>Installing php extensions</h3>
<p><strong>Script: <code>install_php_extensions.sh</code></strong></p>
<p>When php extensions are missing, googling will often point to answers for normal linux systems using <code>apt-get</code> or <code>yum</code>,  e.g. <code>sudo apt-get install php-xdebug</code>. But for the official docker images, the recommended way is using the  <a target="_blank" href="https://github.com/docker-library/docs/blob/master/php/README.md#how-to-install-more-php-extensions">docker-php-ext-configure, docker-php-ext-install, and docker-php-ext-enable helper scripts</a>. Unfortunately, some extensions have rather complicated dependencies, so that the installation fails. Fortunately, there is a great project on Github called  <a target="_blank" href="https://github.com/mlocati/docker-php-extension-installer">docker-php-extension-installer</a> that takes care of that for us and is super easy to use:</p>
<pre><code>FROM php:<span class="hljs-number">7.3</span><span class="hljs-operator">-</span>cli

ADD https:<span class="hljs-comment">//raw.githubusercontent.com/mlocati/docker-php-extension-installer/master/install-php-extensions /usr/local/bin/</span>

RUN chmod uga<span class="hljs-operator">+</span>x <span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>local<span class="hljs-operator">/</span>bin<span class="hljs-operator">/</span>install<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>extensions <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> sync <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> install<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>extensions xdebug
</code></pre><p>The readme also contains an  <a target="_blank" href="https://github.com/mlocati/docker-php-extension-installer#supported-php-extensions">overview of supported extension</a>  per PHP version. To ensure that all of our PHP containers have the same extensions, we provide the following script:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

<span class="hljs-comment"># add wget</span>
apt-get update -yqq &amp;&amp; apt-get -f install -yyq wget

<span class="hljs-comment"># download helper script</span>
wget -q -O /usr/<span class="hljs-built_in">local</span>/bin/install-php-extensions https://raw.githubusercontent.com/mlocati/docker-php-extension-installer/master/install-php-extensions \
    || (<span class="hljs-built_in">echo</span> <span class="hljs-string">"Failed while downloading php extension installer!"</span>; <span class="hljs-built_in">exit</span> 1)

<span class="hljs-comment"># install all required extensions</span>
chmod uga+x /usr/<span class="hljs-built_in">local</span>/bin/install-php-extensions &amp;&amp; sync &amp;&amp; install-php-extensions \
    xdebug \
    opcache \
;
</code></pre><p>If you're not sure which extensions are required by your application, give the  <a target="_blank" href="https://github.com/maglnet/ComposerRequireChecker">ComposerRequireChecker</a> a try.</p>
<h3 id="heading-installing-common-software"><a id="installing-common-software"></a>Installing common software</h3>
<p><strong>Script: <code>install_software.sh</code></strong></p>
<p>There is a certain set of software that I want to have readily available in every container. Since this a development  setup, I'd prioritize ease of use / debug over performance / image size, so this might seem like a little "too much". I think I'm also kinda spoiled by my Homestead past, because it's so damn convenient to have everything right at your fingertips :)</p>
<p>Anyway, the script is straight forward: </p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

apt-get update -yqq &amp;&amp; apt-get install -yqq \
    curl \
    dnsutils \
    gdb \
    git \
    htop \
    iputils-ping \
    iproute2 \
    ltrace \
    make \
    procps \
    strace \
    sudo \
    sysstat \
    unzip \
    vim \
    wget \
;
</code></pre><p>Notes:</p>
<ul>
<li>this list should match <strong>your own set of go-to tools</strong>. I'm fairly open to adding new stuff here if it speeds up the
dev workflow. But if you don't require some of the tools, get rid of them.</li>
<li>sorting the software alphabetically is a good practice to avoid unnecessary duplicates. Don't do this by hand, though!
If you're using an IDE / established text editor, chances are high that this is either a build-in functionality or
there's a plugin available. I'm using <a target="_blank" href="https://plugins.jetbrains.com/plugin/5919-lines-sorter">Lines Sorter for PhpStorm</a></li>
</ul>
<h3 id="heading-cleaning-up"><a id="cleaning-up"></a>Cleaning up</h3>
<p><strong>Script: <code>cleanup.sh</code></strong></p>
<p>Nice and simple:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

apt-get clean
rm -rf /var/lib/apt/lists/* \
       /tmp/* \
       /var/tmp/* \
       /var/<span class="hljs-built_in">log</span>/lastlog \
       /var/<span class="hljs-built_in">log</span>/faillog
</code></pre><h3 id="heading-using-entrypoint-for-pre-run-configuration"><a id="using-entrypoint-for-pre-run-configuration"></a>Using <code>ENTRYPOINT</code> for pre-run configuration</h3>
<p>Docker went back to the unix roots with the  <a target="_blank" href="https://en.wikipedia.org/wiki/Unix_philosophy#Do_One_Thing_and_Do_It_Well">do on thing and do it well philosophy</a> which is  manifested in the <a target="_blank" href="https://medium.freecodecamp.org/docker-entrypoint-cmd-dockerfile-best-practices-abc591c30e21"><code>CMD</code> and <code>ENTRYPOINT</code> instructions</a>.</p>
<p>As I had a hard time understanding those instructions when I started with Docker, here's my take at a layman's terms description:</p>
<ul>
<li>since a container should do one thing, we need to specify that thing. That's what we do with <code>ENTRYPOINT</code>. Concrete examples:<ul>
<li>a <code>mysql</code> container should probably run the <code>mysqld</code> daemon</li>
<li>a <code>php-fpm</code> container.. well, <code>php-fpm</code></li>
</ul>
</li>
<li>the <code>CMD</code> is passed as the default argument to the <code>ENTRYPOINT</code></li>
<li>the <code>ENTRYPOINT</code> is executed every time we <em>run</em> a container. Some things can't be done during build but only at runtime
(e.g. find the IP of the host from within a container - see section 
<a target="_blank" href="providing-host-docker-internal-for-linux-host-systems">Providing <code>host.docker.internal</code> for linux host systems</a>
) - <code>ENTRYPOINT</code> is a good solution for that problem</li>
<li>technically, we can only override an already existing <code>ENTRYPOINT</code> from the base image. But: We can structure the new 
<code>ENTRYPOINT</code> like a <a target="_blank" href="https://en.wikipedia.org/wiki/Decorator_pattern">decorator</a> by adding <code>exec "$@"</code> at the end to 
simulate inheritance from the parent image</li>
</ul>
<p>To expand on the last point, consider the default  <a target="_blank" href="https://github.com/docker-library/php/blob/640a30e8ff27b1ad7523a212522472fda84d56ff/7.3/stretch/fpm/docker-php-entrypoint"><code>ENTRYPOINT</code> of the current [2019-02-23; PHP 7.3] <code>php-fpm</code> image</a> </p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

<span class="hljs-built_in">set</span> -e

<span class="hljs-comment"># first arg is `-f` or `--some-option`</span>
<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">${1#-}</span>"</span> != <span class="hljs-string">"<span class="hljs-variable">$1</span>"</span> ]; <span class="hljs-keyword">then</span>
    <span class="hljs-built_in">set</span> -- php-fpm <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
<span class="hljs-keyword">fi</span>

<span class="hljs-built_in">exec</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
</code></pre><p>In the <a target="_blank" href="https://github.com/docker-library/php/blob/640a30e8ff27b1ad7523a212522472fda84d56ff/7.3/stretch/fpm/Dockerfile#L223">corresponding Dockerfile</a> we find the following instructions: </p>
<pre><code># <span class="hljs-selector-attr">[...]</span>
<span class="hljs-selector-tag">ENTRYPOINT</span> <span class="hljs-selector-attr">[<span class="hljs-string">"docker-php-entrypoint"</span>]</span>
# <span class="hljs-selector-attr">[...]</span>
<span class="hljs-selector-tag">CMD</span> <span class="hljs-selector-attr">[<span class="hljs-string">"php-fpm"</span>]</span>
</code></pre><p>That means: When we run the container it will pass the string "php-fpm" to the <code>ENTRYPOINT</code> script <code>docker-php-entrypoint</code>  as argument which will then execute it (due to the <code>exec "$@"</code> instruction at the end): </p>
<pre><code><span class="hljs-string">$</span> <span class="hljs-string">docker</span> <span class="hljs-string">run</span> <span class="hljs-string">--name</span> <span class="hljs-string">test</span> <span class="hljs-string">--rm</span> <span class="hljs-string">php:fpm</span>
[<span class="hljs-number">23</span><span class="hljs-string">-Feb-2019</span> <span class="hljs-number">14</span><span class="hljs-string">:49:20</span>] <span class="hljs-attr">NOTICE:</span> <span class="hljs-string">fpm</span> <span class="hljs-string">is</span> <span class="hljs-string">running,</span> <span class="hljs-string">pid</span> <span class="hljs-number">1</span>
[<span class="hljs-number">23</span><span class="hljs-string">-Feb-2019</span> <span class="hljs-number">14</span><span class="hljs-string">:49:20</span>] <span class="hljs-attr">NOTICE:</span> <span class="hljs-string">ready</span> <span class="hljs-string">to</span> <span class="hljs-string">handle</span> <span class="hljs-string">connections</span>
<span class="hljs-comment"># php-fpm is running</span>
<span class="hljs-comment"># Hit ctrl + c to close the connection</span>
<span class="hljs-string">$</span> <span class="hljs-string">docker</span> <span class="hljs-string">stop</span> <span class="hljs-string">test</span>
</code></pre><p>We could now override the default <code>CMD</code> "php-fpm" with something else, e.g. a simple <code>echo "hello"</code>. The <code>ENTRYPOINT</code> will happily execute it: </p>
<pre><code>$ docker run <span class="hljs-operator">-</span><span class="hljs-operator">-</span>name test <span class="hljs-operator">-</span><span class="hljs-operator">-</span>rm php:fpm echo <span class="hljs-string">"hello"</span>
hello
</code></pre><p>But now the <code>php-fpm</code> process isn't started any more. How can we echo "hello" but still keep the fpm process running?
By adding our own <code>ENTRYPOINT</code> script: </p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">'hello'</span>

<span class="hljs-built_in">exec</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
</code></pre><p>Full example (using <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/build/#build-with--">stdin to pass the Dockerfile</a>  via <a target="_blank" href="https://stackoverflow.com/q/2953081/413531">Heredoc string</a>) </p>
<pre><code>$ docker build <span class="hljs-operator">-</span>t my<span class="hljs-operator">-</span>fpm <span class="hljs-operator">-</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">&lt;</span><span class="hljs-string">'EOF'</span>
FROM php:fpm

RUN  touch <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
  <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> echo <span class="hljs-string">"#!/bin/sh"</span> <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
  <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> echo <span class="hljs-string">"echo 'hello'"</span> <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
  <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> echo <span class="hljs-string">"exec \"\$@\""</span> <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
  <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> chmod <span class="hljs-operator">+</span>x <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
  <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> cat <span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span> \
;

ENTRYPOINT [<span class="hljs-string">"/usr/bin/my-entrypoint.sh"</span>, <span class="hljs-string">"docker-php-entrypoint"</span>]
CMD [<span class="hljs-string">"php-fpm"</span>]
EOF
</code></pre><p>Note that we added the <code>ENTRYPOINT</code> of the parent image <code>docker-php-entrypoint</code> as argument to our own <code>ENTRYPOINT</code> script <code>/usr/bin/my-entrypoint.sh</code> so that we don't loose its functionality. And we need to define the <code>CMD</code> instruction explicitly, because the one from the parent image is <a target="_blank" href="https://stackoverflow.com/a/49031590/413531">automatically removed once we define our own <code>ENTRYPOINT</code></a>.</p>
<p>But: It works:  </p>
<pre><code><span class="hljs-string">$</span> <span class="hljs-string">docker</span> <span class="hljs-string">run</span> <span class="hljs-string">--name</span> <span class="hljs-string">test</span> <span class="hljs-string">--rm</span> <span class="hljs-string">my-fpm</span>
<span class="hljs-string">hello</span>
[<span class="hljs-number">23</span><span class="hljs-string">-Feb-2019</span> <span class="hljs-number">15</span><span class="hljs-string">:43:25</span>] <span class="hljs-attr">NOTICE:</span> <span class="hljs-string">fpm</span> <span class="hljs-string">is</span> <span class="hljs-string">running,</span> <span class="hljs-string">pid</span> <span class="hljs-number">1</span>
[<span class="hljs-number">23</span><span class="hljs-string">-Feb-2019</span> <span class="hljs-number">15</span><span class="hljs-string">:43:25</span>] <span class="hljs-attr">NOTICE:</span> <span class="hljs-string">ready</span> <span class="hljs-string">to</span> <span class="hljs-string">handle</span> <span class="hljs-string">connections</span>
<span class="hljs-comment"># Hit ctrl + c to close the connection</span>
<span class="hljs-string">$</span> <span class="hljs-string">docker</span> <span class="hljs-string">stop</span> <span class="hljs-string">test</span>
</code></pre><h4 id="heading-providing-hostdockerinternal-for-linux-host-systems"><a id="providing-host-docker-internal-for-linux-host-systems"></a>Providing <code>host.docker.internal</code> for linux host systems</h4>
<p><strong>Script: <code>docker-entrypoint/resolve-docker-host-ip.sh</code></strong></p>
<p>In the previous part of this tutorial series, I explained how to build the  <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker">Docker container in a way that it plays nice with PhpStorm and Xdebug</a>.  The key parts were SSH access and the magical <code>host.docker.internal</code> DNS entry. This works great for Docker Desktop (Windows and Mac) but not for Linux. The DNS entry <a target="_blank" href="https://github.com/docker/for-linux/issues/264">doesn't exist there</a>.  Since we rely on that entry  <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#fix-xdebug-on-phpstorm-when-run-from-a-docker-container">to make debugging possible</a>, we will set it "manually" <a target="_blank" href="https://stackoverflow.com/a/24049165/413531">if the host doesn't exist</a>  with the following script  (inspired by the article <a target="_blank" href="https://dev.to/bufferings/access-host-from-a-docker-container-4099">Access host from a docker container</a>):</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>

<span class="hljs-built_in">set</span> -e

HOST_DOMAIN=<span class="hljs-string">"host.docker.internal"</span>

<span class="hljs-comment"># check if the host exists - this will fail on linux</span>
<span class="hljs-keyword">if</span> dig <span class="hljs-variable">${HOST_DOMAIN}</span> | grep -q <span class="hljs-string">'NXDOMAIN'</span>
<span class="hljs-keyword">then</span>
  <span class="hljs-comment"># resolve the host IP</span>
  HOST_IP=$(ip route | awk <span class="hljs-string">'NR==1 {print $3}'</span>)
  <span class="hljs-comment"># and write it to the hosts file</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$HOST_IP</span>\t<span class="hljs-variable">$HOST_DOMAIN</span>"</span> &gt;&gt; /etc/hosts
<span class="hljs-keyword">fi</span>

<span class="hljs-built_in">exec</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
</code></pre><p>The script is placed at <code>.shared/docker-entrypoint/resolve-docker-host-ip.sh</code> and added as <code>ENTRYPOINT</code> in the Dockerfile via </p>
<pre><code>COPY .shared/scripts<span class="hljs-operator">/</span> <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>

RUN mkdir <span class="hljs-operator">-</span>p <span class="hljs-operator">/</span>bin<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>entrypoint<span class="hljs-operator">/</span> \
 <span class="hljs-operator">&amp;</span><span class="hljs-operator">&amp;</span> cp <span class="hljs-operator">/</span>tmp<span class="hljs-operator">/</span>scripts<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>entrypoint<span class="hljs-comment">/* /bin/docker-entrypoint/ \
 &amp;&amp; chmod +x -R /bin/docker-entrypoint/ \
;

ENTRYPOINT ["/bin/docker-entrypoint/resolve-docker-host-ip.sh", ...]</span>
</code></pre><p>Notes:</p>
<ul>
<li>since this script depends on runtime configuration, we need to run it as an <code>ENTRYPOINT</code></li>
<li>there is no need to explicitly check for the OS type - we simply make sure that the DNS entry exists
and add it if it doesn't</li>
<li>we're using <code>dig</code> (package <code>dnsutils</code>) and <code>ip</code> (package <code>iproute2</code>) which need to be installed 
during the build time of the container. Tip: If you need to figure out the package for a specific command,
give <a target="_blank" href="https://command-not-found.com/">https://command-not-found.com/</a> a try. See the 
<a target="_blank" href="https://command-not-found.com/dig">entry for <code>dig</code></a> for instance.</li>
<li>this workaround is only required in containers we want to debug via xdebug</li>
</ul>
<h2 id="heading-wrapping-up"><a id="wrapping-up"></a>Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. Apart from that, you should now have a running docker setup for your local PHP development as well as a nice "flow" to get started each day.</p>
<p>In the next part of this tutorial, we will  <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">add some more containers (php workers, mysql, redis)</a> and use <a target="_blank" href="https://www.pascallandau.com/blog/run-laravel-9-docker-in-2022/">a fresh installation of Laravel 9</a> to make use of them.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)</p>
]]></content:encoded></item><item><title><![CDATA[PhpStorm, Docker and Xdebug 3 on PHP 8.1 in 2022 [Tutorial Part 3]]]></title><description><![CDATA[How to configure PhpStorm and Xdebug to run PHP in Docker for php-fpm, cli and daemon worker processes in 2022. This article appeared first on at PhpStorm…]]></description><link>https://pascallandau.hashnode.dev/phpstorm-docker-and-xdebug-3-on-php-81-in-2022-tutorial-part-3</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/phpstorm-docker-and-xdebug-3-on-php-81-in-2022-tutorial-part-3</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[PHP]]></category><category><![CDATA[PhpStorm]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Fri, 24 Jun 2022 08:25:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1656059193627/tY2xvdLy5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-phpstorm-docker-and-xdebug-3-on-php-81-in-2022">PhpStorm, Docker and Xdebug 3 on PHP 8.1 in 2022</h1>
<p>How to configure PhpStorm and Xdebug to run PHP in Docker for php-fpm, cli and daemon worker processes in 2022.</p>
<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/phpstorm-docker-xdebug-3-php-8-1-in-2022/">PhpStorm, Docker and Xdebug 3 on PHP 8.1 in 2022 [Tutorial Part 4.2]</a></p><p></p>
<hr />

<p>In this part of the tutorial series on developing PHP on Docker we  will <strong>setup our local development environment to be used by PhpStorm and Xdebug</strong>. We will also  ensure that we can run <strong>PHPUnit tests from the command line as well as from PhpStorm</strong> and throw  the tool <code>strace</code> into the mix for debugging long running processes.</p>
<div class="youtube">
<iframe width="560" height="315" src="https://www.youtube.com/embed/bZ1MiynqT98"></iframe>
</div>

<p>All code samples are publicly available in my <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.   You find the branch for this tutorial at  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-4-2-phpstorm-docker-xdebug-3-php-8-1-in-2022">part-4-2-phpstorm-docker-xdebug-3-php-8-1-in-2022</a></p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/run-laravel-9-docker-in-2022/">Run Laravel 9 on Docker in 2022</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>

<p><a id="table-of-contents"> </a>
</p>
<h2 id="heading-table-of-contents">Table of contents</h2>

<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#install-tools">Install Tools</a><ul>
<li><a class="post-section-overview" href="#install-composer">Install composer</a></li>
<li><a class="post-section-overview" href="#install-xdebug">Install Xdebug</a></li>
<li><a class="post-section-overview" href="#install-phpunit">Install PHPUnit</a></li>
<li><a class="post-section-overview" href="#install-ssh">Install SSH</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#setup-phpstorm">Setup PhpStorm</a><ul>
<li><a class="post-section-overview" href="#ssh-configuration">SSH Configuration</a></li>
<li><a class="post-section-overview" href="#php-interpreter">PHP Interpreter</a></li>
<li><a class="post-section-overview" href="#phpunit">PHPUnit</a></li>
<li><a class="post-section-overview" href="#debugging">Debugging</a><ul>
<li><a class="post-section-overview" href="#debug-code-executed-via-phpstorm">Debug code executed via PhpStorm</a></li>
<li><a class="post-section-overview" href="#debug-code-executed-via-php-fpm-cli-or-from-a-worker">Debug code executed via php-fpm, cli or from a worker</a><ul>
<li><a class="post-section-overview" href="#php-fpm">php-fpm</a></li>
<li><a class="post-section-overview" href="#cli">cli</a></li>
<li><a class="post-section-overview" href="#php-workers">php-workers</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#strace">strace</a></li>
<li><a class="post-section-overview" href="#wrapping-up">Wrapping up</a></li>
</ul>


<p><a id="introduction"> </a>
</p>
<h2 id="heading-introduction">Introduction</h2>
<p>This article is mostly an update of <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/">Setting up PhpStorm with Xdebug for local development on Docker</a> but will also cover the "remaining cases" of <strong>debugging php-fpm</strong> and <strong>php worker processes</strong>. </p>
<p>We will still rely on an <strong>always-running docker setup</strong> that we connect to via an SSH Configuration instead of using the  <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#run-debug-a-php-script-on-docker-server">built-in docker-compose capabilities</a> as I feel it's closer to what we do in CI / production. However, we will <strong>not use SSH keys</strong>  any longer but simply authenticate via password. This reduces complexity and removes any  pesky warnings regarding "SSH keys being exposed in a repository".</p>

<p><a id="install-tools"> </a>
</p>
<h2 id="heading-install-tools">Install Tools</h2>

<p><a id="install-composer"> </a>
</p>
<h3 id="heading-install-composer-composerhttpsgetcomposerorg-is-installed-by-pulling-the-official-composer-docker-imagehttpshubdockercomcomposer-and-simply-copying-the-composer-executable-over-to-the-base-php-image-in-addition-composer-needs-the-extensions-mbstring-and-phar">Install composer <a target="_blank" href="https://getcomposer.org/">Composer</a> is installed by pulling  <a target="_blank" href="https://hub.docker.com/_/composer">the official composer docker image</a> and simply "copying" the  composer executable over to the base php image. In addition, composer needs the extensions <code>mbstring</code> and <code>phar</code></h3>
<pre><code><span class="hljs-comment"># File: .docker/images/php/base/Dockerfile</span>

ARG ALPINE_VERSION
ARG COMPOSER_VERSION
FROM composer:${COMPOSER_VERSION} as composer
FROM alpine:${ALPINE_VERSION} as base

<span class="hljs-comment"># ...</span>

RUN apk add --update --<span class="hljs-keyword">no</span>-cache  \
        php-mbstring~=${TARGET_PHP_VERSION} \
        php-phar~=${TARGET_PHP_VERSION} \

<span class="hljs-comment"># ...</span>

COPY --from=composer /usr/bin/composer /usr/<span class="hljs-keyword">local</span>/bin/composer
</code></pre><p>Because we want our build to be deterministic, we "pin" the composer version by adding a  <code>COMPOSER_VERSION</code> variable to the <code>.docker/.env</code> file </p>
<pre><code class="lang-dotenv">COMPOSER_VERSION=2.2.5
</code></pre>
<p>and using it in <code>.docker/docker-compose/docker-compose-php-base.yml</code>:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">php-base:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">args:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-string">COMPOSER_VERSION=${COMPOSER_VERSION?}</span>
</code></pre>

<p><a id="install-xdebug"> </a>
</p>
<h3 id="heading-install-xdebug-install-the-extension-via-apk-only-for-the-local-target">Install Xdebug Install the extension via <code>apk</code> (only for the <code>local</code> target):</h3>
<pre><code class="lang-Dockerfile"># File: .docker/images/php/base/Dockerfile

FROM base as local

RUN apk add --no-cache --update \
        php-xdebug~=${TARGET_PHP_VERSION} \
    # ensure that xdebug is not enabled by default
    &amp;&amp; rm -f /etc/php8/conf.d/00_xdebug.ini
</code></pre>
<p>We also don't want to enable <code>xdebug</code> immediately but only when we need it (due to the decrease  in performance when the extension is enabled), hence we remove the default config file and  disable the extension in the application <code>.ini</code> file</p>
<pre><code><span class="hljs-comment"># File: .docker/images/php/base/conf.d/zz-app-local.ini</span>

<span class="hljs-comment">; <span class="hljs-doctag">Note:</span></span>
<span class="hljs-comment">; Remove the comment ; to enable debugging</span>
<span class="hljs-comment">;zend_extension=xdebug</span>
<span class="hljs-attr">xdebug.client_host</span>=host.docker.internal
<span class="hljs-attr">xdebug.start_with_request</span>=<span class="hljs-literal">yes</span>
<span class="hljs-attr">xdebug.mode</span>=debug
</code></pre><p>See <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#fix-xdebug-on-phpstorm-when-run-from-a-docker">Fix Xdebug on PhpStorm when run from a Docker container</a> for an explanation of the <code>xdebug.client_host=host.docker.internal</code> setting (previously called <code>xdebug.remote_host</code> in xdebug &lt; 3). This will still work out of the box for Docker Desktop, but for Linux users we need to add the  <a target="_blank" href="https://github.com/docker/for-linux/issues/264#issuecomment-965465879"><code>host-gateway</code> magic reference</a>
<strong>to all PHP containers</strong> (we can't add it to the php base image because this is a runtime setting):</p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">service:</span>
    <span class="hljs-attr">extra_hosts:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">host.docker.internal:host-gateway</span>
</code></pre>
<p>Finally, we need to add  <a target="_blank" href="https://www.jetbrains.com/help/phpstorm/debugging-a-php-cli-script.html">the environment variable <code>PHP_IDE_CONFIG</code></a>
<strong>to all PHP containers</strong>. The variable is defined as <code>PHP_IDE_CONFIG=serverName=dofroscra</code>, where  "dofroscra" is the name of the server that we will configure later for debugging. Because we  need the same value in multiple places, the variable is configured in <code>.docker/.env</code>:</p>
<pre><code><span class="hljs-attr">PHP_IDE_CONFIG</span>=serverName=dofroscra
</code></pre><p>And then added in <code>.docker/docker-compose/docker-compose.local.yml</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">php-fpm:</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">PHP_IDE_CONFIG=${PHP_IDE_CONFIG?}</span>

  <span class="hljs-attr">php-worker:</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">PHP_IDE_CONFIG=${PHP_IDE_CONFIG?}</span>

  <span class="hljs-attr">application:</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">PHP_IDE_CONFIG=${PHP_IDE_CONFIG?}</span>
</code></pre>

<p><a id="install-phpunit"> </a>
</p>
<h3 id="heading-install-phpunit-phpunit-will-be-installed-via-composer-but-will-not-be-baked-into-the-image-for-local-development-thus-we-must-run-composer-require-in-the-container-to-make-this-more-convenient-a-make-target-for-running-arbitrary-composer-commands-is-added-in-make01-00-application-setupmk">Install PHPUnit PHPUnit will be installed via <code>composer</code> but will not be "baked into the image" for local  development. Thus, we must run <code>composer require</code> <strong>in the container</strong>. To make this more  convenient a make target for running arbitrary composer commands is added in  <code>.make/01-00-application-setup.mk</code>:</h3>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: composer</span>
<span class="hljs-section">composer: ## Run composer commands. Specify the command e.g. via ARGS="install"</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> composer <span class="hljs-variable">$(ARGS)</span>;
</code></pre>
<p>This allows me to run <code>make composer ARGS="install"</code> from the host system to execute <code>composer  install</code> in the container. In consequence, <code>composer</code> will use the PHP version and extensions of  the <code>application</code> container to install the dependencies, yet I will still see the installed files locally because the codebase is configured as a volume for the container.</p>
<p>Before installing phpunit, we must add the required extensions <code>dom</code> and <code>xml</code> to the container</p>
<pre><code><span class="hljs-comment"># File: .docker/images/php/base/Dockerfile</span>

<span class="hljs-comment"># ...</span>

<span class="hljs-attribute">RUN</span> apk add --update --<span class="hljs-literal">no</span>-cache  \
        php-dom~=<span class="hljs-variable">${TARGET_PHP_VERSION}</span> \
        php-xml~=<span class="hljs-variable">${TARGET_PHP_VERSION}</span> \
</code></pre><p>as well as rebuild and restart the docker setup via </p>
<pre><code><span class="hljs-built_in">make</span> docker-build
<span class="hljs-built_in">make</span> docker-down
<span class="hljs-built_in">make</span> docker-up
</code></pre><p>Now we can add phpunit via</p>
<pre><code><span class="hljs-built_in">make</span> composer ARGS=<span class="hljs-string">'require "phpunit/phpunit"'</span>
</code></pre><p>which will create a <code>composer.json</code> file and setup up the <code>vendor/</code> directory:</p>
<pre><code>$ make composer ARGS<span class="hljs-operator">=</span><span class="hljs-string">'require "phpunit/phpunit"'</span>
Using version <span class="hljs-operator">^</span><span class="hljs-number">9.5</span> <span class="hljs-keyword">for</span> phpunit<span class="hljs-operator">/</span>phpunit
./composer.json has been created
Running composer update phpunit<span class="hljs-operator">/</span>phpunit
Loading composer repositories with package information
Updating dependencies
...
</code></pre><p><strong>CAUTION</strong>: If you <strong>run into the following permission error</strong> at this step, you are likely using  Linux and  haven't set the <code>APP_USER_ID</code> and <code>APP_GROUP_ID</code> variables as described in the previous article under  <a target="_blank" href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/#solving-permission-issues">Solving permission issues</a>.</p>
<pre><code class="lang-text">make composer ARGS='req phpunit/phpunit' ENV=local TAG=latest DOCKER_REGISTRY=docker.io DOCKER_NAMESPACE=dofroscra APP_USER_NAME=application APP_GROUP_NAME=application docker-compose -p dofroscra_local --env-file ./.docker/.env -f ./.docker/docker-compose/docker-compose.yml -f ./.docker/docker-compose/docker-compose.local.yml exec -T --user application application composer req phpunit/phpunit
./composer.json is not writable.
make: *** [.make/01-00-application-setup.mk:14: composer] Error 1
</code></pre>
<p>I have also added </p>
<ul>
<li>a minimal <code>phpunit.xml</code> config file</li>
<li>a test case at <code>tests/SomeTest.php</code> </li>
<li>and a new Makefile for "anything related to qa" at <code>.make/01-02-application-qa.mk</code>:</li>
</ul>
<pre><code class="lang-Makefile"><span class="hljs-comment">##@ [Application: QA]</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: test</span>
<span class="hljs-section">test: ## Run the test suite </span>
    <span class="hljs-variable">$(EXECUTE_IN_WORKER_CONTAINER)</span> vendor/bin/phpunit -c phpunit.xml
</code></pre>
<p>So I can run tests simply via <code>make test</code></p>
<pre><code>$ make test
ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker vendor<span class="hljs-operator">/</span>bin<span class="hljs-operator">/</span>phpunit
PHPUnit <span class="hljs-number">9.5</span><span class="hljs-number">.13</span> by Sebastian Bergmann and contributors.

.                                                                   <span class="hljs-number">1</span> <span class="hljs-operator">/</span> <span class="hljs-number">1</span> (<span class="hljs-number">100</span><span class="hljs-operator">%</span>)

Time: 00:00<span class="hljs-number">.324</span>, Memory: <span class="hljs-number">4.00</span> MB

OK (<span class="hljs-number">1</span> test, <span class="hljs-number">1</span> assertion)
</code></pre>
<p><a id="install-ssh"> </a>
</p>
<h3 id="heading-install-ssh">Install SSH</h3>
<p>We will execute commands from PhpStorm via ssh in the <code>application</code> container. As mentioned, we  won't use a key file for authentication but will instead simply use a password that is  configured via the <code>APP_SSH_PASSWORD</code> variable in <code>.docker/.env</code> and passed to the image in  <code>.docker/docker-compose/docker-compose.local.yml</code>. In addition, we map port <code>2222</code> from the  host system to port <code>22</code> of the application container and make sure that the codebase is shared as a volume between host and container</p>
<pre><code class="lang-yaml">  <span class="hljs-attr">application:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">args:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-string">APP_SSH_PASSWORD=${APP_SSH_PASSWORD?}</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">${APP_CODE_PATH_HOST?}:${APP_CODE_PATH_CONTAINER?}</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"${APPLICATION_SSH_HOST_PORT:-2222}:22"</span>
</code></pre>
<p>The container already contains <code>openssh</code> and sets the password</p>
<pre><code class="lang-Dockerfile">ARG BASE_IMAGE
FROM ${BASE_IMAGE} as base

FROM base as local

RUN apk add --no-cache --update \
        openssh

ARG APP_SSH_PASSWORD
RUN echo "$APP_USER_NAME:$APP_SSH_PASSWORD" | chpasswd 2&gt;&amp;1

# Required to start sshd, otherwise the container will error out on startup with the message
# "sshd: no hostkeys available -- exiting."
# @see https://stackoverflow.com/a/65348102/413531 
RUN ssh-keygen -A

# we use SSH deployment configuration in PhpStorm for local development
EXPOSE 22

CMD ["/usr/sbin/sshd", "-D"]
</code></pre>

<p><a id="setup-phpstorm"> </a>
</p>
<h2 id="heading-setup-phpstorm">Setup PhpStorm</h2>
<p>We will configure a remote PHP interpreter that uses an SSH connection to run commands in the  <code>application</code> container. Before,  <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#configure-the-deployment-configuration">we have been using an <code>SFTP Deployment configuration</code></a> , which was kinda confusing ("What is SFTP doing here?"), so we will use an  <a target="_blank" href="https://www.jetbrains.com/help/phpstorm/create-ssh-configurations.html">SSH Configuration</a>  instead and configure the path mappings in the <strong>Cli Interpreter</strong> interface</p>

<p><a id="ssh-configuration"> </a>
</p>
<h3 id="heading-ssh-configuration">SSH Configuration</h3>
<p>At <code>File | Settings | Tools | SSH Configurations</code> create a new SSH Configuration named  "Docker PHP Tutorial" with the following settings </p>
<ul>
<li>Host: 127.0.0.1</li>
<li>Port: see <code>APPLICATION_SSH_HOST_PORT</code> in <code>.docker/docker-compose/docker-compose.local.yml</code></li>
<li>User name: see <code>APP_USER_NAME</code> in <code>.make/.env</code></li>
<li>Authentication type: Password</li>
<li>Password: see <code>APP_SSH_PASSWORD</code> in <code>.docker/.env</code></li>
</ul>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-ssh-configuration.PNG">![PhpStorm SSH Configuration](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-ssh-configuration.PNG "PhpStorm SSH Configuration")</a></p>

<p><a id="php-interpreter"> </a>
</p>
<h3 id="heading-php-interpreter">PHP Interpreter</h3>
<p>At <code>File | Settings | PHP</code> add a new PHP CLI interpreter that uses the new SSH Configuration</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter.PNG">![PhpStorm new CLI interpreter](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter.PNG "PhpStorm new CLI interpreter")</a></p>
<p>In addition, we define the <strong>path to the xdebug extension</strong> because it is disabled by default but PhpStorm can enable it automatically if required. You can find the path in the <code>application</code> container via</p>
<pre><code>root:<span class="hljs-regexp">/var/</span>www/app# php -i | grep extension_dir
extension_dir =&gt; <span class="hljs-regexp">/usr/</span>lib/php8/<span class="hljs-function"><span class="hljs-params">modules</span> =&gt;</span> /usr/lib/php8/modules
root:<span class="hljs-regexp">/var/</span>www/app# ll /usr/lib/php8/modules | grep xdebug
-rwxr-xr-x    <span class="hljs-number">1</span> root     root        <span class="hljs-number">303936</span> Jan  <span class="hljs-number">9</span> <span class="hljs-number">00</span>:<span class="hljs-number">21</span> xdebug.so
</code></pre><p>We still need to  <a target="_blank" href="https://www.pascallandau.com/blog/setup-phpstorm-with-xdebug-on-docker/#fix-xdebug-on-phpstorm-when-run-from-a-docker-container">Fix Xdebug on PhpStorm when run from a Docker container</a> by adding a custom PHP option for <code>xdebug.client_host=host.docker.internal</code>. That's the same value we use in <code>.docker/images/php/base/conf.d/zz-app-local.ini</code>.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter-xdebug.PNG">![PhpStorm Xdebug settings for the CLI interpreter](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter-xdebug.PNG "PhpStorm Xdebug settings for the CLI interpreter")</a></p>
<p>In the interpreter overview we must now configure the <strong>path mappings</strong> so that PhpStorm knows "which local file belongs to which remote one". The remote folder is defined in <code>.docker/.env</code> via</p>
<pre><code class="lang-dotenv">APP_CODE_PATH_CONTAINER=/var/www/app
</code></pre>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter-path-mappings.PNG">![PhpStorm path mappings for the CLI interpreter](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-cli-interpreter-path-mappings.PNG "PhpStorm path mappings for the CLI interpreter")</a></p>
<p>Afterwards we can set a breakpoint e.g. in <code>setup.php</code> and start debugging:</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint.PNG">![PhpStorm debugging breakpoint](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint.PNG "PhpStorm debugging breakpoint")</a></p>
<p>The screenshot shows that PhpStorm adds the Xdebug extension that we defined previously.</p>

<p><a id="phpunit"> </a>
</p>
<h3 id="heading-phpunit">PHPUnit</h3>
<p><code>phpunit</code> is configured via <code>File | Settings | PHP | Test Frameworks</code>. First, we select the interpreter that we just added</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-phpunit-interpreter.PNG">![Set up phpunit in PhpStorm](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-phpunit-interpreter.PNG "Set up phpunit in PhpStorm")</a></p>
<p>Then, we add the paths to the composer autoload script and the <code>phpunit.xml</code> configuration file.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-phpunit-settings.PNG">![phpunit settings in PhpStorm](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-phpunit-settings.PNG "phpunit settings in PhpStorm")</a></p>
<p>PhpStorm will now execute tests using the PHP interpreter in the <code>application</code> container</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-run-phpunit-test.PNG">![Run a phpunit test in PhpStorm](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-run-phpunit-test.PNG "Run a phpunit test in PhpStorm")</a></p>

<p><a id="debugging"> </a>
</p>
<h3 id="heading-debugging">Debugging</h3>
<p>First of all, if you haven't already please also take a look at the  <a target="_blank" href="https://xdebug.org/docs/step_debug">official xdebug documentation</a>. Derick is doing a great job  at explaining xdebug in detail including some helpful videos like <a target="_blank" href="https://www.youtube.com/watch?v=4opFac50Vwo">Xdebug 3: Xdebug with Docker and PhpStorm in 5 minutes</a></p>

<p><a id="debug-code-executed-via-phpstorm"> </a>
</p>
<h4 id="heading-debug-code-executed-via-phpstorm">Debug code executed via PhpStorm</h4>
<p>This should already work out of the box. Simply set a break point, right-click on a file and choose  "Debug '...'"</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint.PNG">![PhpStorm debugging breakpoint](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint.PNG "PhpStorm debugging breakpoint")</a></p>

<p><a id="debug-code-executed-via-php-fpm-cli-or-from-a-worker"> </a>
</p>
<h4 id="heading-debug-code-executed-via-php-fpm-cli-or-from-a-worker">Debug code executed via php-fpm, cli or from a worker</h4>
<p>For code that is executed "directly" by a container without PhpStorm, we first need to enable  <code>xdebug</code> in the container by removing the <code>;</code> in front of the extension in  <code>/etc/php8/conf.d/zz-app-local.ini</code></p>
<pre><code><span class="hljs-comment">; <span class="hljs-doctag">Note:</span></span>
<span class="hljs-comment">; Remove the comment ; to enable debugging</span>
<span class="hljs-attr">zend_extension</span>=xdebug
</code></pre><p>To make this a little more convenient, we use dedicated make recipes for those actions in <code>.make/01-01-application-commands.mk</code></p>
<pre><code class="lang-Makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: execute-in-container</span>
<span class="hljs-section">execute-in-container: ## Execute a command in a container. E.g. via "make execute-in-container DOCKER_SERVICE_NAME=php-fpm COMMAND="echo 'hello'"</span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span>,,$(<span class="hljs-built_in">error</span> DOCKER_SERVICE_NAME is undefined)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(COMMAND)</span>,,$(<span class="hljs-built_in">error</span> COMMAND is undefined)</span>)
    <span class="hljs-variable">$(EXECUTE_IN_CONTAINER)</span> <span class="hljs-variable">$(COMMAND)</span>;

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: enable-xdebug</span>
<span class="hljs-section">enable-xdebug: ## Enable xdebug in the given container specified by "DOCKER_SERVICE_NAME". E.g. "make enable-xdebug DOCKER_SERVICE_NAME=php-fpm"</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> execute-in-container APP_USER_NAME=<span class="hljs-string">"root"</span> DOCKER_SERVICE_NAME=<span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span> COMMAND=<span class="hljs-string">"sed -i 's/.*zend_extension=xdebug/zend_extension=xdebug/' '/etc/php8/conf.d/zz-app-local.ini'"</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: disable-xdebug</span>
<span class="hljs-section">disable-xdebug: ## Disable xdebug in the given container specified by "DOCKER_SERVICE_NAME". E.g. "make enable-xdebug DOCKER_SERVICE_NAME=php-fpm"</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> execute-in-container APP_USER_NAME=<span class="hljs-string">"root"</span> DOCKER_SERVICE_NAME=<span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span> COMMAND=<span class="hljs-string">"sed -i 's/.*zend_extension=xdebug/;zend_extension=xdebug/' '/etc/php8/conf.d/zz-app-local.ini'"</span>
</code></pre>
<p>To capture incoming requests, we need to make PhpStorm listen for PHP Debug connections via <code>Run | Start Listening for PHP Debug Connections</code>. </p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-start-listening-for-debug-connections.PNG">![PhpStorm: Start Listening for PHP Debug Connections](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-start-listening-for-debug-connections.PNG "PhpStorm: Start Listening for PHP Debug Connections")</a></p>
<p>The corresponding ports are configured at <code>File | Settings | PHP | Debug</code>. In Xdebug &lt; 3 the  default port was <code>9000</code> and in <a target="_blank" href="https://xdebug.org/docs/all_settings#client_port">Xdebug 3 it is <code>9003</code></a> </p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-ports.PNG">![PhpStorm: configure xdebug ports](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-ports.PNG "PhpStorm: configure xdebug ports")</a></p>
<p>Finally, we need to add a server via <code>File | Settings | PHP | Servers</code></p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-server.PNG">![PhpStorm: configure a server](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-server.PNG "PhpStorm: configure a server")</a></p>
<p>The name of the server must match the value of the <code>serverName</code> key in the environment variable  <code>PHP_IDE_CONFIG</code> that we configured previously as <code>serverName=dofroscra</code>.</p>

<p><a id="php-fpm"> </a>
</p>
<h5 id="heading-php-fpm">php-fpm</h5>
<p>For <code>php-fpm</code> we must <a target="_blank" href="https://stackoverflow.com/a/43076457">restart the <code>php-fpm</code> process without restarting the container</a> after we have activated <code>xdebug</code> via</p>
<pre><code><span class="hljs-attribute">kill</span> -USR<span class="hljs-number">2</span> <span class="hljs-number">1</span>
</code></pre><p>Since this is a pain to remember, we add a make target in <code>.make/01-01-application-commands.mk</code></p>
<pre><code class="lang-Makefile"><span class="hljs-comment"># @see https://stackoverflow.com/a/43076457</span>
<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: restart-php-fpm</span>
<span class="hljs-section">restart-php-fpm: ## Restart the php-fpm service</span>
    <span class="hljs-string">"<span class="hljs-variable">$(MAKE)</span>"</span> execute-in-container DOCKER_SERVICE_NAME=<span class="hljs-variable">$(DOCKER_SERVICE_NAME_PHP_FPM)</span> COMMAND=<span class="hljs-string">"kill -USR2 1"</span>
</code></pre>
<p>So we can now simply run</p>
<pre><code>make enable<span class="hljs-operator">-</span>xdebug DOCKER_SERVICE_NAME<span class="hljs-operator">=</span>php<span class="hljs-operator">-</span>fpm
make restart<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>fpm
</code></pre><p>Setting a breakpoint in <code>public/index.php</code> and opening <a target="_blank" href="http://127.0.0.1/">http://127.0.0.1/</a> in a browser or via <code>curl http://127.0.0.1/</code> will halt the execution as expected.</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-php-fpm.PNG">![PhpStorm debugging breakpoint for php-fpm](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-php-fpm.PNG "PhpStorm debugging breakpoint for php-fpm")</a></p>

<p><a id="cli"> </a>
</p>
<h5 id="heading-cli">cli</h5>
<p>Instead of triggering a PHP script via HTTP request, we can also run CLI scripts - think of the  <code>make setup-db</code> target for instance. To debug such invocations, we need to follow the same steps as before:</p>
<ul>
<li>enable the <code>xdebug</code> extension in the <code>application</code> container</li>
<li>"Listening for PHP Debug Connections" from PhpStorm</li>
</ul>
<p>Running the following make targets will trigger a breakpoint in <code>setup.php</code>:</p>
<pre><code>make enable<span class="hljs-operator">-</span>xdebug DOCKER_SERVICE_NAME<span class="hljs-operator">=</span>application
make setup<span class="hljs-operator">-</span>db
</code></pre><p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-cli.PNG">![PhpStorm debugging breakpoint for cli](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-cli.PNG "PhpStorm debugging breakpoint for cli")</a></p>

<p><a id="php-workers"> </a>
</p>
<h5 id="heading-php-workers">php-workers</h5>
<p>And finally the same thing for long running PHP processes (aka workers). Just as before:</p>
<ul>
<li>enable the <code>xdebug</code> extension in the <code>php-worker</code> container</li>
<li>"Listening for PHP Debug Connections" from PhpStorm</li>
<li>restart the php workers  </li>
</ul>
<p>Running the following make targets will trigger a breakpoint in <code>worker.php</code>:</p>
<pre><code>make enable<span class="hljs-operator">-</span>xdebug DOCKER_SERVICE_NAME<span class="hljs-operator">=</span>php<span class="hljs-operator">-</span>worker
make restart<span class="hljs-operator">-</span>workers
</code></pre><p><a target="_blank" href="https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-php-worker.PNG">![PhpStorm debugging breakpoint for php-workers](https://www.pascallandau.com/img/phpstorm-docker-xdebug-3-php-8-1-in-2022/phpstorm-xdebug-breakpoint-php-worker.PNG "PhpStorm debugging breakpoint for php-workers")</a></p>

<p><a id="strace"> </a>
</p>
<h2 id="heading-strace">strace</h2>
<p><a target="_blank" href="https://strace.io/">strace</a> is a great tool for debugging long running processes that I've  adopted after reading <a target="_blank" href="https://derickrethans.nl/what-is-php-doing.html">What is PHP doing?</a>. I've added it to the php base image:</p>
<pre><code class="lang-Dockerfile">RUN apk add --update --no-cache \
        strace
</code></pre>
<p>You can attach to any running process via <code>sudo strace -p $processId</code> - BUT that doesn't work  out of the box on docker and will fail with the error message</p>
<pre><code><span class="hljs-attribute">strace</span>: <span class="hljs-attribute">attach</span>: ptrace(PTRACE_SEIZE, <span class="hljs-number">1</span>): Operation not permitted
</code></pre><p>This is caused by a security measure from docker and  <a target="_blank" href="https://stackoverflow.com/a/46676868">can be circumvented</a> by adding</p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">service:</span>
    <span class="hljs-attr">cap_add:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"SYS_PTRACE"</span>
    <span class="hljs-attr">security_opt:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"seccomp=unconfined"</span>
</code></pre>
<p>in <code>.docker/docker-compose/docker-compose.local.yml</code> <strong>to all PHP containers</strong>. After  rebuilding and restarting the docker setup, you can now e.g. log in the <code>php-worker</code> container and run <code>strace</code> on a php worker process:</p>
<pre><code><span class="hljs-attribute">application</span>:/var/www/app# ps aux
<span class="hljs-attribute">PID</span>   USER     TIME  COMMAND
    <span class="hljs-attribute">1</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> {supervisord} /usr/bin/python<span class="hljs-number">3</span> /usr/bin/supervisord
    <span class="hljs-attribute">7</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> php /var/www/app/worker.php
    <span class="hljs-attribute">8</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> php /var/www/app/worker.php
    <span class="hljs-attribute">9</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> php /var/www/app/worker.php
   <span class="hljs-attribute">10</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> php /var/www/app/worker.php
   <span class="hljs-attribute">11</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> bash
   <span class="hljs-attribute">20</span> applicat  <span class="hljs-number">0</span>:<span class="hljs-number">00</span> ps aux
<span class="hljs-attribute">application</span>:/var/www/app# sudo strace -p <span class="hljs-number">7</span>
<span class="hljs-attribute">strace</span>: Process <span class="hljs-number">7</span> attached
<span class="hljs-attribute">restart_syscall</span>(&lt;... resuming interrupted read ...&gt;) = <span class="hljs-number">0</span>
<span class="hljs-attribute">poll</span>([{fd=<span class="hljs-number">4</span>, events=POLLIN|POLLPRI|POLLERR|POLLHUP}], <span class="hljs-number">1</span>, <span class="hljs-number">0</span>) = <span class="hljs-number">0</span> (Timeout)
<span class="hljs-attribute">sendto</span>(<span class="hljs-number">4</span>, <span class="hljs-string">"*2\r\n$4\r\nRPOP\r\n$5\r\nqueue\r\n"</span>, <span class="hljs-number">25</span>, MSG_DONTWAIT, NULL, <span class="hljs-number">0</span>) = <span class="hljs-number">25</span>
<span class="hljs-attribute">poll</span>([{fd=<span class="hljs-number">4</span>, events=POLLIN|POLLPRI|POLLERR|POLLHUP}], <span class="hljs-number">1</span>, <span class="hljs-number">0</span>) = <span class="hljs-number">1</span> ([{fd=<span class="hljs-number">4</span>, revents=POLLIN}])
<span class="hljs-attribute">recvfrom</span>(<span class="hljs-number">4</span>, <span class="hljs-string">"$"</span>, <span class="hljs-number">1</span>, MSG_PEEK, NULL, NULL) = <span class="hljs-number">1</span>
</code></pre>
<p><a id="wrapping-up"> </a>
</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. Apart from that, you should now have a fully configured development setup that works with PhpStorm as your IDE.</p>
<p>In the next part of this tutorial, we will  <a target="_blank" href="https://www.pascallandau.com/blog/run-laravel-9-docker-in-2022/">use a fresh installation of Laravel on top of our setup</a>.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)
;</p>
]]></content:encoded></item><item><title><![CDATA[Docker from scratch for PHP 8.1 Applications in 2022 [Tutorial Part 2]]]></title><description><![CDATA[This article appeared first on at Docker from scratch for PHP 8.1 Applications in 2022 [Tutorial Part 4.1] In the fourth part of this tutorial series on…]]></description><link>https://pascallandau.hashnode.dev/docker-from-scratch-for-php-81-applications-in-2022-tutorial-part-2</link><guid isPermaLink="true">https://pascallandau.hashnode.dev/docker-from-scratch-for-php-81-applications-in-2022-tutorial-part-2</guid><category><![CDATA[Developer]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Pascal Landau]]></dc:creator><pubDate>Mon, 20 Jun 2022 07:47:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1655711601016/3TytBdNKK.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p></p><p>This article appeared first on <a href="https://www.pascallandau.com/">https://www.pascallandau.com/</a> at <a href="https://www.pascallandau.com/blog/docker-from-scratch-for-php-applications-in-2022/">Docker from scratch for PHP 8.1 Applications in 2022 [Tutorial Part 4.1]</a></p><p></p>
<hr />

<p>In the fourth part of this tutorial series on developing PHP on Docker we will revisit the previous tutorials and update some things to be up-to-date in 2022. </p>
<div class="youtube">
<iframe width="560" height="315" src="https://www.youtube.com/embed/NuSWKx9FSso"></iframe>
</div>

<p><strong>All code samples are publicly available</strong> in my <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/">Docker PHP Tutorial repository on Github</a>.   You find the branch for this tutorial at  <a target="_blank" href="https://github.com/paslandau/docker-php-tutorial/tree/part-4-1-docker-from-scratch-for-php-applications-in-2022">part-4-1-docker-from-scratch-for-php-applications-in-2022</a></p>
<p><strong>All published parts of the Docker PHP Tutorial</strong> are collected under a dedicated page at <a target="_blank" href="https://www.pascallandau.com/docker-php-tutorial/">Docker PHP Tutorial</a>. The previous part was <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/">Structuring the Docker setup for PHP Projects</a> and the following one is <a target="_blank" href="https://www.pascallandau.com/blog/phpstorm-docker-xdebug-3-php-8-1-in-2022/">PhpStorm, Docker and Xdebug 3 on PHP 8.1 in 2022</a>.</p>
<p>If you want to follow along, please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get <strong>automatic notifications</strong> when the next part comes out :)</p>

<p><a id="table-of-contents"> </a>
</p>
<h2 id="heading-table-of-contents">Table of contents</h2>

<ul>
<li><a class="post-section-overview" href="#introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#local-docker-setup">Local docker setup</a></li>
<li><a class="post-section-overview" href="#docker">Docker</a><ul>
<li><a class="post-section-overview" href="#docker-compose">docker-compose</a><ul>
<li><a class="post-section-overview" href="#docker-env-file-and-required-env-variables"><code>.docker/.env</code> file and required ENV variables</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#images">Images</a><ul>
<li><a class="post-section-overview" href="#php-images">PHP images</a><ul>
<li><a class="post-section-overview" href="#env-vs-arg">ENV vs ARG</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#image-naming-convention">Image naming convention</a></li>
<li><a class="post-section-overview" href="#environments-and-build-targets">Environments and build targets</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#makefile">Makefile</a><ul>
<li><a class="post-section-overview" href="#make-mk-includes"><code>.make/*.mk</code> includes</a></li>
<li><a class="post-section-overview" href="#shared-variables-make-env">Shared variables: <code>.make/.env</code></a><ul>
<li><a class="post-section-overview" href="#manual-modifications">Manual modifications</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#enforce-required-parameters">Enforce required parameters</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#make-docker-3">Make + Docker = &lt;3</a><ul>
<li><a class="post-section-overview" href="#ensuring-the-build-order">Ensuring the build order</a></li>
<li><a class="post-section-overview" href="#run-commands-in-the-docker-containers">Run commands in the docker containers</a><ul>
<li><a class="post-section-overview" href="#solving-permission-issues">Solving permission issues</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="post-section-overview" href="#php-poc">PHP POC</a></li>
<li><a class="post-section-overview" href="#wrapping-up">Wrapping up</a></li>
</ul>


<p><a id="introduction"> </a>
</p>
<h2 id="heading-introduction">Introduction</h2>
<p>If you have read the previous tutorial <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/">Structuring the Docker setup for PHP Projects</a> you might encounter some significant changes. The tutorial was published over 2 years ago,  Docker has evolved and I have learned more about it. Plus, I gathered practical  experience (good and bad) with the previous setup. I would now consider most of the points under <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#fundamentals-on-building-the-containers">Fundamentals on building the containers</a> as either "not required" or simply "overengineered / too complex". To be concrete:</p>
<ul>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#setting-the-timezone">Setting the timezone</a><ul>
<li>not required if the default is already UTC (which is almost always the case)</li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#synchronizing-file-and-folder-ownership-on-shared-volumes">Synchronizing file and folder ownership on shared volumes</a><ul>
<li>this is only an issue if files need to be <strong>modified</strong> by containers and the host system - which
is only really relevant for the PHP containers</li>
<li>in addition, I would recommend adding a completely new user (e.g. <code>application</code>) instead of
re-using an existing one like <code>www-data</code> - this simplifies the whole user setup <em>a lot</em></li>
<li>from now on we will be using <code>application</code> as the user name (<code>APP_USER_NAME</code>) and <code>10000</code> the 
user id (<code>APP_USER_ID</code>; following the best practice to 
<a target="_blank" href="https://github.com/hexops/dockerfile#do-not-use-a-uid-below-10000">not use a UID below 10,000</a>)</li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#modifying-configuration-files">Modifying configuration files</a><ul>
<li>just use <code>sed</code> - no need for a dedicated script</li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#installing-php-extensions">Installing php extensions</a><ul>
<li>see <a class="post-section-overview" href="#php-images">PHP images</a> - will now be done via <code>apk add</code></li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#installing-common-software">Installing common software</a><ul>
<li>see <a class="post-section-overview" href="#php-images">PHP images</a> - since there is only one base image there is no need for a
dedicated script</li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#cleaning-up">Cleaning up</a><ul>
<li>didn't really make sense because the "cleaned up files" were already part of a previous layer</li>
<li>we might "bring it back" later when we optimize the image size to speed up the pushing/pulling
of the images to/from the registry</li>
</ul>
</li>
<li><a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#providing-host-docker-internal-for-linux-host-systems">Providing host.docker.internal for linux host systems</a><ul>
<li>can now be done via
the <a target="_blank" href="https://github.com/docker/for-linux/issues/264#issuecomment-965465879"><code>host-gateway</code> magic reference</a><pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
     <span class="hljs-attr">myservice:</span>
          <span class="hljs-attr">extra_hosts:</span>
            <span class="hljs-bullet">-</span> <span class="hljs-string">host.docker.internal:host-gateway</span>
</code></pre>
</li>
<li>thus, no custom entrypoint is required any longer</li>
</ul>
</li>
</ul>

<p><a id="local-docker-setup"> </a>
</p>
<h2 id="heading-local-docker-setup">Local docker setup</h2>
<p>The goal of this part is the introduction of a working local setup <strong>without development tools</strong>. In other words: We want the bare minimum to have something running locally.</p>
<p>The main components are:</p>
<ul>
<li>the <code>make</code> setup in the <code>Makefile</code> and in the <code>.make/</code> directory</li>
<li>the docker setup in the <code>.docker/</code> directory</li>
<li>some PHP files that act as a POC for the end2end functionality of the docker setup</li>
</ul>
<p>Check out the code via</p>
<pre><code><span class="hljs-attribute">git</span> checkout part_<span class="hljs-number">4</span>_section_<span class="hljs-number">1</span>_docker_from_scratch_for_php_applications_in_<span class="hljs-number">2022</span>_code_structure
</code></pre><p>initialize it via</p>
<pre><code><span class="hljs-built_in">make</span> <span class="hljs-built_in">make</span>-init
<span class="hljs-built_in">make</span> docker-build
</code></pre><p>and run it via</p>
<pre><code><span class="hljs-built_in">make</span> docker-up
</code></pre><p>Now you can access the web interface via <a target="_blank" href="http://127.0.0.1">http://127.0.0.1</a>. The following  diagram shows how the containers are connected</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-containers.PNG">![Docker container connections](https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-containers.PNG "Docker container connections")</a></p>
<p>See also the <a class="post-section-overview" href="#php-poc">PHP POC</a> for a full test of the setup.</p>

<p><a id="docker"> </a>
</p>
<h2 id="heading-docker">Docker</h2>
<p>The docker setup consists of</p>
<ul>
<li>an nginx container as a webserver</li>
<li>a MySQL database container</li>
<li>a Redis container that acts as a queue</li>
<li>a php base image that is used by<ul>
<li>a php worker container that spawns multiple PHP worker processes via <code>supervisor</code></li>
<li>a php-fpm container as a backend for the nginx container</li>
<li>an application container that we use to run commands</li>
</ul>
</li>
</ul>
<p><a target="_blank" href="https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-images.PNG">![Docker images](https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-images.PNG "Docker images")</a></p>
<p>We keep the <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#the-docker-folder"><code>.docker/</code> directory from the previous tutorial</a> , though it will be split into <code>docker-compose/</code> and <code>images/</code> like so:</p>
<pre><code>.
└── .docker/
    ├── docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>
    <span class="hljs-operator">|</span>   ├── docker<span class="hljs-operator">-</span>compose.yml
    <span class="hljs-operator">|</span>   └── <span class="hljs-operator">&lt;</span>other docker<span class="hljs-operator">-</span>compose files<span class="hljs-operator">&gt;</span>
    ├── images<span class="hljs-operator">/</span>
    <span class="hljs-operator">|</span>   ├── nginx<span class="hljs-operator">/</span>
    <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   ├── Dockerfile
    <span class="hljs-operator">|</span>   <span class="hljs-operator">|</span>   └── <span class="hljs-operator">&lt;</span>other files <span class="hljs-keyword">for</span> the nginx image<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">|</span>   └── <span class="hljs-operator">&lt;</span>other folders <span class="hljs-keyword">for</span> docker images<span class="hljs-operator">&gt;</span>
    ├── .env
    └── .env.example
</code></pre>
<p><a id="docker-compose"> </a>
</p>
<h3 id="heading-docker-compose">docker-compose</h3>
<p>All images are <strong>build</strong> via <code>docker-compose</code> because the <code>docker-compose.yml</code> file(s) provide a nice abstraction layer for the build configuration. In addition, we can also use it to <strong>orchestrate</strong> the containers, i.e. control volumes, port mappings, networking, etc. - as well as start and stop them via <code>docker-compose up</code> and <code>docker-compose down</code>.</p>
<p>FYI: Even though it is <em>convenient</em> to use <code>docker-compose</code> for both things, I found it also to make the setup more complex than it needs to be when running things later in production (when we are <em>not</em> using <code>docker-compose</code> any longer). I believe the problem here is that some modifications are ONLY required for building while others are ONLY required for running - and combining both in the same file yields a certain amount of noise. But: It is what it is.</p>
<p>We use three separate <code>docker-compose.yml</code> files:</p>
<ul>
<li>docker-compose.yml<ul>
<li>contains all information valid for all environments</li>
</ul>
</li>
<li>docker-compose.local.yml<ul>
<li>contains information specific to the <code>local</code> environment,
see <a class="post-section-overview" href="#environments-and-build-targets">Environments and build targets</a></li>
</ul>
</li>
<li>docker-compose-php-base.yml<ul>
<li>contains information for building the php base image, see <a class="post-section-overview" href="#php-images">PHP images</a></li>
</ul>
</li>
</ul>

<p><a id="docker-env-file-and-required-env-variables"> </a>
</p>
<h4 id="heading-dockerenv-file-and-required-env-variables"><code>.docker/.env</code> file and required ENV variables</h4>
<p>In our docker setup we basically have 3 different types of variables:</p>
<ol>
<li>variables that <strong>depend on the local setup</strong> of an individual developer, e.g. the
<code>NGINX_HOST_HTTP_PORT</code> on the host machine (because the default one might already be in use) 2. variables that <strong>are used in multiple images</strong>, e.g. the location of the codebase within a
container's file system 3. variables that <strong>hold information that is "likely to change"</strong>, e.g. the exact version of a base
image</li>
</ol>
<p>Since - again - we strive to retain a single source of truth, we extract the information as variables and put them in a <code>.docker/.env</code> file. In a perfect world, I would like to separate these different types in different files - but <code>docker-compose</code> only allows a single <code>.env</code> file, see e.g. <a target="_blank" href="https://github.com/docker/compose/issues/6170#issuecomment-443523663">this comment</a>. If the file does not exist, it is copied from <code>.docker/.env.example</code>.</p>
<p>The variables are then used in the <code>docker-compose.yml</code> file(s). I found it to be "the least  painful" to always use the <a target="_blank" href="https://docs.docker.com/compose/environment-variables/#substitute-environment-variables-in-compose-files"><code>?</code> modifier on variables</a> so that <code>docker-compose</code> <strong>fails immediately if the variable is missing</strong>.</p>
<p>Note: Some variables are expected to be passed via environment variables when <code>docker-compose</code> is invoked (i.e. they are required but not defined in the <code>.env</code> file; see also  <a class="post-section-overview" href="#shared-variables-make-env">Shared variables: <code>.make/.env</code></a></p>

<p><a id="images"> </a>
</p>
<h3 id="heading-images">Images</h3>
<p>For <strong>MySQL</strong> and <strong>redis</strong> we do not use custom-built images but instead <strong>use the official ones <em>directly</em></strong> and configure them through environment variables when starting the containers. In production, we won't use docker anyway for these services but instead rely on the managed versions, e.g.</p>
<ul>
<li>redis =&gt; <a target="_blank" href="https://cloud.google.com/memorystore/docs/redis">Memorystore for Redis (GCP)</a> or
<a target="_blank" href="https://aws.amazon.com/de/elasticache/redis/">ElastiCache für Redis (AWS)</a></li>
<li>mysql =&gt; <a target="_blank" href="https://cloud.google.com/sql/docs/mysql">Cloud SQL for MySQL (GCP)</a> or
<a target="_blank" href="https://aws.amazon.com/de/rds/mysql/">RDS for MySQL (AWS)</a></li>
</ul>
<p>The remaining containers are defined in their respective subdirectories in the <code>.docker/images/</code> directory, e.g. the image for the <code>nginx</code> container is build via the <code>Dockerfile</code> located in <code>.docker/images/nginx/Dockerfile</code>.</p>

<p><a id="php-images"> </a>
</p>
<h4 id="heading-php-images">PHP images</h4>
<p>We need 3 different PHP images (fpm, workers, application) and use a slightly different approach than in <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/">Structuring the Docker setup for PHP Projects</a>:</p>
<p>Instead of using the <a target="_blank" href="https://hub.docker.com/_/php">official PHP base images</a> (i.e. cli or fpm), we use a "plain" alpine base image and install PHP and the required extensions manually in it. This allows us to build a common base image for all PHP images. Benefits:</p>
<ul>
<li>a central place for shared tools and configuration (no more need for a <code>.shared/</code> directory)</li>
<li>reduced image size when pushing the individual images (the base image is recognized as a layer and
thus "already exists")</li>
<li>installing extensions via <code>apk add</code> is <strong>a lot</strong> faster than via <code>docker-php-ext-install</code></li>
</ul>
<p>This new approach has two major downsides:</p>
<ul>
<li>we depend on the alpine release cycle of PHP (and PHP extensions)</li>
<li>the image build process is more complex, because we must build the base image first before we can
build the final images</li>
</ul>
<p>Fortunately, both issues can be solved rather easily:</p>
<ul>
<li><a target="_blank" href="https://github.com/codecasts/php-alpine">codecasts/php-alpine</a> maintains an <code>apk</code> repository with
the latest PHP versions for alpine</li>
<li>we use a dedicated <code>make</code> target to build the images instead of invoking <code>docker-compose</code>
directly - this enables us to define a "build order" (base first, rest after) while still having
to run only a single command as a developer 
(see <a class="post-section-overview" href="#ensuring-the-build-order">Ensuring the build order</a>)</li>
</ul>

<p><a id="env-vs-arg"> </a>
</p>
<h5 id="heading-env-vs-arg">ENV vs ARG</h5>
<p>I've noticed that some build arguments are required in multiple PHP containers, e.g. the name of the application user defined in the <code>APP_USER_NAME</code> ENV variable. The username is needed</p>
<ul>
<li>in the base image to create the user</li>
<li>in the fpm image to define the user that runs the fpm processes (see <code>php-fpm.d/www.conf</code>)</li>
<li>in the worker image to define the user that runs the worker processes (
see <code>supervisor/supervisord.conf</code>)</li>
</ul>
<p>Instead of passing the name to all images via build argument, i.e.</p>
<ul>
<li>define it explicitly under <code>services.*.build.args</code> in the <code>docker-compose.yml</code> file</li>
<li>"retrieve" it in the Dockerfile via <code>ARG APP_USER_NAME</code></li>
</ul>
<p>I've opted to make the username available as an <code>ENV</code> variable in the base image via</p>
<pre><code><span class="hljs-attribute">ARG</span> APP_USER_NAME
ENV APP_USER_NAME=<span class="hljs-variable">${APP_USER_NAME}</span>
</code></pre><p>and thus be able to access it in the child images directly, I can now write</p>
<pre><code>RUN <span class="hljs-built_in">echo</span> <span class="hljs-variable">${APP_USER_NAME}</span>
</code></pre><p>instead of</p>
<pre><code>ARG APP_USER_NAME
RUN <span class="hljs-built_in">echo</span> <span class="hljs-variable">${APP_USER_NAME}</span>
</code></pre><p>I'm not 100% certain that I like this approach as I'm more or less "abusing" ENV variables in ways that they are likely not intended ("Why would the username need to be stored as an ENV variable?") -
but I also don't see any other practical downside yet.</p>

<p><a id="image-naming-convention"> </a>
</p>
<h4 id="heading-image-naming-convention">Image naming convention</h4>
<p>Defining a <a target="_blank" href="https://windsock.io/referencing-docker-images/">fully qualified name for images</a> will make it much easier to reference the images later, e.g. when pushing them to the registry.</p>
<p>The naming convention for the images is <code>$(DOCKER_REGISTRY)/$(DOCKER_NAMESPACE)/$(DOCKER_SERVICE_NAME)-$(ENV)</code>, e.g.</p>
<pre><code>                   docker.io/dofroscra<span class="hljs-operator">/</span>nginx<span class="hljs-operator">-</span>local
$(DOCKER_REGISTRY)<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">^</span>          <span class="hljs-operator">^</span>        <span class="hljs-operator">^</span>     <span class="hljs-operator">^</span>        docker.io
$(DOCKER_NAMESPACE)<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">^</span>        <span class="hljs-operator">^</span>     <span class="hljs-operator">^</span>        dofroscra
$(DOCKER_SERVICE_NAME)<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">^</span>     <span class="hljs-operator">^</span>        nginx
$(ENV)<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">^</span>        local
</code></pre><p>and it is used as value for <code>services.*.image</code>, e.g. for <code>nginx</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">nginx:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">${DOCKER_REGISTRY?}/${DOCKER_NAMESPACE?}/nginx-${ENV?}:${TAG?}</span>
</code></pre>
<p>In case you are wondering: <code>dofroscra</code> stems from <strong>Do</strong>cker <strong>Fro</strong>m <strong>Scra</strong>tch</p>

<p><a id="environments-and-build-targets"> </a>
</p>
<h4 id="heading-environments-and-build-targets">Environments and build targets</h4>
<p>Our final goal is a setup that we can use for</p>
<ul>
<li>local development</li>
<li>in a CI/CD pipeline</li>
<li>in production</li>
</ul>
<p>and even though we strive to for a <a target="_blank" href="https://12factor.net/dev-prod-parity">parity between those different environments</a>, there will be differences due to fundamentally different requirements. E.g.</p>
<ul>
<li>on <em>production</em> I want a container <strong>including the sourcecode without any test dependencies</strong></li>
<li>on <em>CI</em> I want a container <strong>including the sourcecode WITH test dependencies</strong></li>
<li>on <em>local</em> I want a container <strong>that mounts the sourcecode from my host (including 
dependencies)</strong></li>
</ul>
<p>This is reflected through the <code>ENV</code> environment variable. We use it in two places:</p>
<ol>
<li>as part of the image name as a suffix of the service name
(see <a class="post-section-overview" href="#image-naming-convention">Image naming convention</a>) 2. to specify
the <a target="_blank" href="https://docs.docker.com/engine/reference/commandline/build/#specifying-target-build-stage---target">target build stage</a></li>
</ol>
<p>See the <code>docker-compose-php-base.yml</code> file for example:</p>
<pre><code>services:
  php<span class="hljs-operator">-</span>base:
    image: ${DOCKER_REGISTRY?}<span class="hljs-operator">/</span>${DOCKER_NAMESPACE?}<span class="hljs-operator">/</span>php<span class="hljs-operator">-</span>base<span class="hljs-operator">-</span>${ENV?}:${TAG?}
    build:
      dockerfile: images<span class="hljs-operator">/</span>php<span class="hljs-operator">/</span>base<span class="hljs-operator">/</span>Dockerfile
      target: ${ENV?}
</code></pre><p>Using <strong>multiple targets in the same Dockerfile</strong> enables us to keep a <strong>common base</strong> but also  include <strong>environment specific instructions</strong>. See the Dockerfile of the <code>php-base</code> image for  example</p>
<pre><code class="lang-Dockerfile">ARG ALPINE_VERSION
FROM composer:${COMPOSER_VERSION} as composer
FROM alpine:${ALPINE_VERSION} as base

RUN apk add --update --no-cache \
        bash

WORKDIR $APP_CODE_PATH

FROM base as local

RUN apk add --no-cache --update \
        mysql-client \
</code></pre>
<ul>
<li>it first defines a <code>base</code> stage that includes software required in all environments</li>
<li>and then defines a <code>local</code> stage that adds additionally a <code>mysql-client</code> that helps us to debug
connectivity issues</li>
</ul>
<p>After the build for <code>local</code> is finished, we end up with an image called <code>php-base-local</code> that used the <code>local</code> build stage as target build stage.</p>

<p><a id="makefile"> </a>
</p>
<h2 id="heading-makefile">Makefile</h2>
<p>In the following section I will <strong>introduce a couple of commands</strong>, e.g. for building and running  containers. And to be honest, I find it kinda challenging to keep them in mind without having to  look up the exact options and arguments. I would <strong>usually create a helper function</strong> or an alias in my  local <code>.bashrc</code> file in a situation like that - but that wouldn't be available to other members of  the team then and it would be very specific to this one project.</p>
<p>Instead we'll use a <strong>self-documenting Makefile</strong> that <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#using-make-as-central-entry-point">acts as the central entrypoint in the application</a>.  Since Makefiles tend to grow over time, I've adopted some strategies to keep them  "sane" via includes, shared variables and better error handling.</p>

<p><a id="make-mk-includes"> </a>
</p>
<h3 id="heading-makemk-includes"><code>.make/*.mk</code> includes</h3>
<p>Over time the <code>make</code> setup will grow substantially, thus we split it into multiple <code>.mk</code> files in the <code>.make/</code> directory. The individual files are prefixed with a number to ensure their order when we include them in the main <code>Makefile</code> via</p>
<pre><code>include .make/<span class="hljs-operator">*</span>.mk
</code></pre><pre><code>.
└── .make/
    ├── 01<span class="hljs-operator">-</span>00<span class="hljs-operator">-</span>application<span class="hljs-operator">-</span>setup.mk
    ├── 01<span class="hljs-operator">-</span>01<span class="hljs-operator">-</span>application<span class="hljs-operator">-</span>commands.mk
    └── 02<span class="hljs-operator">-</span>00<span class="hljs-operator">-</span>docker.mk
</code></pre>
<p><a id="shared-variables-make-env"> </a>
</p>
<h3 id="heading-shared-variables-makeenv">Shared variables: <code>.make/.env</code></h3>
<p>We try to make <strong>shared variables</strong> available here, because we can then pass them on to individual commands as a prefix, e.g.</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: some-target</span>
<span class="hljs-section">some-target: ## Run some target</span>
    ENV_FOO=BAR some_command --baz
</code></pre>
<p>This will make the <code>ENV_FOO</code> available as environment variable to <code>some_command</code>.</p>
<p>Shared variables are used by different components, and we always try to maintain only a <strong>single source of truth</strong>. An example would be the <code>DOCKER_REGISTRY</code> variable that we need to define the <a class="post-section-overview" href="#image-naming-convention">image names of our docker images</a> in the <code>docker-compose.yml</code> files but also when pushing/pulling/deploying images via make targets later. In this case, the variable is required by <code>make</code> as well as <code>docker-compose</code>.</p>
<p>To have a clear separation between variables and "code", we use a <code>.env</code> file located at <code>. make/.env</code>. It can be initialized via</p>
<pre><code><span class="hljs-built_in">make</span> <span class="hljs-built_in">make</span>-init
</code></pre><p>by copying the <code>.make/.env.example</code> to <code>.make/.env</code>.</p>
<pre><code>.
└── .make/
    ├── .make/.env.example
    └── .make/.env
</code></pre><p>The file is included in the main <code>Makefile</code> via</p>
<pre><code><span class="hljs-operator">-</span>include .make/.env
</code></pre><p>The <code>-</code> prefix ensures that make doesn't fail if the file does not exist (yet), see <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Include.html">GNU make: Including Other Makefiles</a>.</p>

<p><a id="manual-modifications"> </a>
</p>
<h4 id="heading-manual-modifications">Manual modifications</h4>
<p>You can always <strong>modify the <code>.make/.env</code> file manually if required</strong>. This might be the  case when you run <code>docker</code> on Linux and need to match the <code>user id</code> of your host system with the  <code>user id</code> of the docker container. It is common that your local user and group have the id  <code>1000</code>. In this case you would add the entries manually to the <code>.make/.env</code> file.</p>
<pre><code class="lang-dotenv">APP_USER_ID=1000
APP_GROUP_ID=1000
</code></pre>
<p>See also section <a class="post-section-overview" href="#solving-permission-issues">Solving permission issues</a>.</p>

<p><a id="enforce-required-parameters"> </a>
</p>
<h3 id="heading-enforce-required-parameters">Enforce required parameters</h3>
<p>We kinda "abuse" make for executing arbitrary commands (instead of building artifacts) and some of those commands require parameters that can be <a target="_blank" href="https://stackoverflow.com/a/2826178/413531">passed as command arguments</a> in the form</p>
<pre><code>make some<span class="hljs-operator">-</span>target FOO<span class="hljs-operator">=</span>bar
</code></pre><p>There is no way to "define" those parameters as we would in a method signature - but we can still ensure to fail as early as possible if a parameter is missing via</p>
<pre><code class="lang-makefile">@<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(FOO)</span>,,$(<span class="hljs-built_in">error</span> FOO is empty <span class="hljs-built_in">or</span> undefined)</span>)
</code></pre>
<p>See also <a target="_blank" href="https://stackoverflow.com/a/10858332/413531">SO: How to abort makefile if variable not set?</a></p>
<p>We use this technique for example to ensure that all required variables are defined when we execute docker targets via the <code>validate-docker-variables</code> precondition target:</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: validate-docker-variables</span>
<span class="hljs-section">validate-docker-variables: </span>
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(TAG)</span>,,$(<span class="hljs-built_in">error</span> TAG is undefined)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(ENV)</span>,,$(<span class="hljs-built_in">error</span> ENV is undefined)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(DOCKER_REGISTRY)</span>,,$(<span class="hljs-built_in">error</span> DOCKER_REGISTRY is undefined - Did you run make-init?)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(DOCKER_NAMESPACE)</span>,,$(<span class="hljs-built_in">error</span> DOCKER_NAMESPACE is undefined - Did you run make-init?)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(APP_USER_NAME)</span>,,$(<span class="hljs-built_in">error</span> APP_USER_NAME is undefined - Did you run make-init?)</span>)
    @<span class="hljs-variable">$(<span class="hljs-built_in">if</span> <span class="hljs-variable">$(APP_GROUP_NAME)</span>,,$(<span class="hljs-built_in">error</span> APP_GROUP_NAME is undefined - Did you run make-init?)</span>)

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>:docker-build-image</span>
<span class="hljs-section">docker-build-image: validate-docker-variables</span>
    <span class="hljs-variable">$(DOCKER_COMPOSE)</span> build <span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span>
</code></pre>

<p><a id="make-docker-3"> </a>
</p>
<h2 id="heading-make-docker">Make + Docker = &lt;3</h2>
<p>We already introduced quite some complexity into our setup:</p>
<ul>
<li>"global" variables (shared between <code>make</code> and <code>docker</code>)</li>
<li>multiple <code>docker-compose.yml</code> files</li>
<li>build dependencies</li>
</ul>
<p>Bringing it all together "manually" is quite an effort and prone to errors. But we can nicely tuck the complexity away in <code>.make/02-00-docker.mk</code> by defining the two variables <code>DOCKER_COMPOSE</code> and <code>DOCKER_COMPOSE_PHP_BASE</code></p>
<pre><code class="lang-makefile">DOCKER_DIR:=./.docker
DOCKER_ENV_FILE:=<span class="hljs-variable">$(DOCKER_DIR)</span>/.env
DOCKER_COMPOSE_DIR:=<span class="hljs-variable">$(DOCKER_DIR)</span>/docker-compose
DOCKER_COMPOSE_FILE:=<span class="hljs-variable">$(DOCKER_COMPOSE_DIR)</span>/docker-compose.yml
DOCKER_COMPOSE_FILE_LOCAL:=<span class="hljs-variable">$(DOCKER_COMPOSE_DIR)</span>/docker-compose.local.yml
DOCKER_COMPOSE_FILE_PHP_BASE:=<span class="hljs-variable">$(DOCKER_COMPOSE_DIR)</span>/docker-compose-php-base.yml
DOCKER_COMPOSE_PROJECT_NAME:=dofroscra_<span class="hljs-variable">$(ENV)</span>

DOCKER_COMPOSE_COMMAND:=ENV=<span class="hljs-variable">$(ENV)</span> \
 TAG=<span class="hljs-variable">$(TAG)</span> \
 DOCKER_REGISTRY=<span class="hljs-variable">$(DOCKER_REGISTRY)</span> \
 DOCKER_NAMESPACE=<span class="hljs-variable">$(DOCKER_NAMESPACE)</span> \
 APP_USER_NAME=<span class="hljs-variable">$(APP_USER_NAME)</span> \
 APP_GROUP_NAME=<span class="hljs-variable">$(APP_GROUP_NAME)</span> \
 docker-compose -p <span class="hljs-variable">$(DOCKER_COMPOSE_PROJECT_NAME)</span> --env-file <span class="hljs-variable">$(DOCKER_ENV_FILE)</span>

DOCKER_COMPOSE:=<span class="hljs-variable">$(DOCKER_COMPOSE_COMMAND)</span> -f <span class="hljs-variable">$(DOCKER_COMPOSE_FILE)</span> -f <span class="hljs-variable">$(DOCKER_COMPOSE_FILE_LOCAL)</span>
DOCKER_COMPOSE_PHP_BASE:=<span class="hljs-variable">$(DOCKER_COMPOSE_COMMAND)</span> -f <span class="hljs-variable">$(DOCKER_COMPOSE_FILE_PHP_BASE)</span>
</code></pre>
<ul>
<li><code>DOCKER_COMPOSE</code> uses <code>docker-compose.yml</code> and extends it with <code>docker-compose.local.yml</code></li>
<li><code>DOCKER_COMPOSE_PHP_BASE</code> uses only <code>docker-compose-php-base.yml</code></li>
</ul>
<p>The variables can then be used later in make recipes.</p>

<p><a id="ensuring-the-build-order"> </a>
</p>
<h3 id="heading-ensuring-the-build-order">Ensuring the build order</h3>
<p>As mentioned under <a class="post-section-overview" href="#php-images">PHP images</a>, we <strong>need to build images in a certain order</strong> and use the following make targets:</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: docker-build-image</span>
<span class="hljs-section">docker-build-image: ## Build all docker images OR a specific image by providing the service name via: make docker-build DOCKER_SERVICE_NAME=&lt;service&gt;</span>
    <span class="hljs-variable">$(DOCKER_COMPOSE)</span> build <span class="hljs-variable">$(DOCKER_SERVICE_NAME)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: docker-build-php</span>
<span class="hljs-section">docker-build-php: ## Build the php base image</span>
    <span class="hljs-variable">$(DOCKER_COMPOSE_PHP_BASE)</span> build <span class="hljs-variable">$(DOCKER_SERVICE_NAME_PHP_BASE)</span>

<span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: docker-build</span>
<span class="hljs-section">docker-build: docker-build-php docker-build-image ## Build the php image and then all other docker images</span>
</code></pre>
<p>As a developer, I can now simply run <code>make docker-build</code> - which will first build the <code>php-base</code>  image via <code>docker-build-php</code> and then build all the remaining images via <code>docker-build-image</code>  (by not specifying the <code>DOCKER_SERVICE_NAME</code> variable, <code>docker-compose</code> will build <strong>all</strong> services  listed in the <code>docker-compose.yml</code> files).</p>
<p>I would argue that the <strong>make recipes themselves are quite readable</strong> and easy to understand but when  we run them with the <a target="_blank" href="https://www.gnu.org/software/make/manual/html_node/Options-Summary.html"><code>-n</code> option</a> to only "Print the recipe that would be executed, but not execute it", we get a feeling for the complexity:</p>
<pre><code>$ make docker<span class="hljs-operator">-</span>build <span class="hljs-operator">-</span>n
ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">-</span>php<span class="hljs-operator">-</span>base.yml build php<span class="hljs-operator">-</span>base
ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml build
</code></pre>
<p><a id="run-commands-in-the-docker-containers"> </a>
</p>
<h3 id="heading-run-commands-in-the-docker-containers">Run commands in the docker containers</h3>
<p>Tooling is an important part in the development workflow. This includes things like linters, static analyzers and testing tools but also "custom" tools geared towards your specific workflow. Those tools usually <strong>require a PHP runtime</strong>. For now, we only have a single "tool" defined in the file <code>setup.php</code>. It ensures that a table called <code>jobs</code> is created.</p>
<p>To run this tool, we must first start the docker setup via <code>make docker-up</code> and then execute the script in the <code>application</code> container. The corresponding target is defined in <code>.make/01-00-application-setup.mk</code>:</p>
<pre><code class="lang-makefile"><span class="hljs-meta"><span class="hljs-meta-keyword">.PHONY</span>: setup-db</span>
<span class="hljs-section">setup-db: ## Setup the DB tables</span>
    <span class="hljs-variable">$(EXECUTE_IN_APPLICATION_CONTAINER)</span> php setup.php <span class="hljs-variable">$(ARGS)</span>;
</code></pre>
<p>which essentially translates to</p>
<pre><code>docker<span class="hljs-operator">-</span>compose exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application application php setup.php
</code></pre><p>if we are outside of a container and to</p>
<pre><code><span class="hljs-selector-tag">php</span> <span class="hljs-selector-tag">setup</span><span class="hljs-selector-class">.php</span>
</code></pre><p>if we are inside a container. That's quite handy, because we can <strong>run the tooling directly from the host system</strong> without having to log into a container.</p>
<p>The "magic" happens in the <code>EXECUTE_IN_APPLICATION_CONTAINER</code> variable that is defined in <code>.make/02-00-docker.mk</code> as</p>
<pre><code class="lang-makefile">EXECUTE_IN_WORKER_CONTAINER?=
EXECUTE_IN_APPLICATION_CONTAINER?=

EXECUTE_IN_CONTAINER?=
<span class="hljs-keyword">ifndef</span> EXECUTE_IN_CONTAINER
    <span class="hljs-comment"># check if 'make' is executed in a docker container, </span>
    <span class="hljs-comment"># see https://stackoverflow.com/a/25518538/413531</span>
    <span class="hljs-comment"># `wildcard $file` checks if $file exists, </span>
    <span class="hljs-comment"># see https://www.gnu.org/software/make/manual/html_node/Wildcard-Function.html</span>
    <span class="hljs-comment"># i.e. if the result is "empty" then $file does NOT exist </span>
    <span class="hljs-comment"># =&gt; we are NOT in a container</span>
    <span class="hljs-keyword">ifeq</span> (<span class="hljs-string">"$(wildcard /.dockerenv)"</span>,<span class="hljs-string">""</span>)
        EXECUTE_IN_CONTAINER=true
    <span class="hljs-keyword">endif</span>
<span class="hljs-keyword">endif</span>
<span class="hljs-keyword">ifeq</span> (<span class="hljs-variable">$(EXECUTE_IN_CONTAINER)</span>,true)
    EXECUTE_IN_APPLICATION_CONTAINER:=<span class="hljs-variable">$(DOCKER_COMPOSE)</span> exec -T --user <span class="hljs-variable">$(APP_USER_NAME)</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME_APPLICATION)</span>
    EXECUTE_IN_WORKER_CONTAINER:=<span class="hljs-variable">$(DOCKER_COMPOSE)</span> exec -T --user <span class="hljs-variable">$(APP_USER_NAME)</span> <span class="hljs-variable">$(DOCKER_SERVICE_NAME_PHP_WORKER)</span>
<span class="hljs-keyword">endif</span>
</code></pre>
<p>We can take a look via <code>-n</code> again to see the resolved recipe on the host system</p>
<pre><code>pascal.landau:/c/_codebase/dofroscra# make setup-db ARGS=<span class="hljs-comment">--drop -n</span>
ENV=<span class="hljs-keyword">local</span> TAG=latest DOCKER_REGISTRY=docker.io DOCKER_NAMESPACE=dofroscra APP_USER_NAME=application APP_GROUP_NAME=application docker-compose -p dofroscra_local <span class="hljs-comment">--env-file ./.docker/.env -f ./.docker/docker-compose/docker-compose.yml -f ./.docker/docker-compose/docker-compose.local.yml exec -T --user application application php setup.php --drop</span>
</code></pre><p>Within a container it looks like this:</p>
<pre><code>root:/var/www/app# make setup-db ARGS=<span class="hljs-comment">--drop -n</span>
php setup.php <span class="hljs-comment">--drop;</span>
</code></pre>
<p><a id="solving-permission-issues"> </a>
</p>
<h4 id="heading-solving-permission-issues">Solving permission issues</h4>
<p>If you are using Linux, you <strong>might run into permission issues when modifying files</strong> that are  shared between the host system and the docker containers <strong>when the user id is not the same</strong> as  explained in section  <a target="_blank" href="https://www.pascallandau.com/blog/structuring-the-docker-setup-for-php-projects/#synchronizing-file-and-folder-ownership-on-shared-volumes">Synchronizing file and folder ownership on shared volumes</a>  of the previous tutorial.</p>
<p>In this case, you need to <a class="post-section-overview" href="#manual-modifications">modify the <code>.make/.env</code> manually</a> and add the <code>APP_USER_ID</code> and <code>APP_GROUP_ID</code> variables according to your local setup. This <strong>must be done <em>before</em> building the images</strong> to ensure that the correct <code>user id</code> is used in the images.</p>
<p>In very rare cases it can lead to problems, because <strong>your local ids will <em>already exist</em> in  the docker containers</strong>. I've personally never run into this problem, but you can read about it  in more detail at  <a target="_blank" href="https://www.joyfulbikeshedding.com/blog/2021-03-15-docker-and-the-host-filesystem-owner-matching-problem.html">Docker and the host filesystem owner matching problem</a>. The author <a target="_blank" href="https://twitter.com/honglilai/status/1509781424345432064">even proposes a general solution</a> via <a target="_blank" href="https://github.com/FooBarWidget/matchhostfsowner">the Github project "FooBarWidget/matchhostfsowner"</a>.</p>

<p><a id="php-poc"> </a>
</p>
<h2 id="heading-php-poc">PHP POC</h2>
<p>To ensure that everything works as expected, the repository contains a minimal PHP proof of concept. By default, port 80 from the host ist forwarded to port 80 of the <code>nginx</code> container.</p>
<p>FYI: I would also recommend to add the following entry <a target="_blank" href="https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/">in the hosts file on the host machine</a></p>
<pre><code>127<span class="hljs-selector-class">.0</span><span class="hljs-selector-class">.0</span><span class="hljs-selector-class">.1</span> <span class="hljs-selector-tag">app</span><span class="hljs-selector-class">.local</span>
</code></pre><p>so that we can access the application via <a target="_blank" href="http://app.local">http://app.local</a> instead of <a target="_blank" href="http://127.0.0.1">http://127.0.0.1</a>.</p>
<p>The files of the POC essentially ensure that the container connections outlined in  <a class="post-section-overview" href="#local-docker-setup">Local docker setup</a> work as expected:</p>
<p><a target="_blank" href="https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-containers.PNG">![Docker container connections](https://www.pascallandau.com/img/docker-from-scratch-for-php-applications-in-2022/docker-containers.PNG "Docker container connections")</a></p>
<ul>
<li><code>dependencies.php</code><ul>
<li>returns configured <code>Redis</code> and <code>PDO</code> objects to talk to the queue and the database</li>
</ul>
</li>
<li><code>setup.php</code><ul>
<li>=&gt; <em>ensures that <code>application</code> can talk to <code>mysql</code></em></li>
</ul>
</li>
<li><code>public/index.php</code><ul>
<li>is the web root file that can be accessed via <a target="_blank" href="http://app.local">http://app.local</a><ul>
<li>=&gt; <em>ensures that <code>nginx</code> and <code>php-fpm</code> are working</em></li>
</ul>
</li>
<li>contains 3 different "routes":<ul>
<li><a target="_blank" href="http://app.local?dispatch=some-job-id">http://app.local?dispatch=some-job-id</a><ul>
<li>dispatches a new "job" with the id <code>some-job-id</code> on the queue to be picked up by a 
worker<ul>
<li>=&gt; <em>ensures that <code>php-fpm</code> can talk to <code>redis</code></em></li>
</ul>
</li>
</ul>
</li>
<li><a target="_blank" href="http://app.local?queue">http://app.local?queue</a><pre><code>  - shows the content of the <span class="hljs-built_in">queue</span>
</code></pre></li>
<li><a target="_blank" href="http://app.local?db">http://app.local?db</a><ul>
<li>shows the content of the database<ul>
<li>=&gt; <em>ensures that <code>php-fpm</code> can talk to <code>mysql</code></em></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><code>worker.php</code><ul>
<li>is started as daemon process in the <code>php-worker</code> container</li>
<li>checks the redis datasbase <code>0</code> for the key <code>"queue"</code> every second</li>
<li>if a value is found it is stored in the <code>jobs</code> table of the database<ul>
<li>=&gt; <em>ensures that <code>php-worker</code> can talk to <code>redis</code> and <code>mysql</code></em></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>A full test scenario is defined in <code>test.sh</code> and looks like this:</p>
<pre><code>$ bash test.sh


  Building the docker setup


<span class="hljs-comment">//...</span>


  Starting the docker setup


<span class="hljs-comment">//...</span>


  Clearing DB


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application application php setup.php <span class="hljs-operator">-</span><span class="hljs-operator">-</span>drop;
Dropping table <span class="hljs-string">'jobs'</span>
Done
Creating table <span class="hljs-string">'jobs'</span>
Done


  Stopping workers


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker supervisorctl stop worker:<span class="hljs-operator">*</span>;
worker:worker_00: stopped
worker:worker_01: stopped
worker:worker_02: stopped
worker:worker_03: stopped


  Ensuring that queue and db are empty


Items in queue
array(<span class="hljs-number">0</span>) {
}
Items in db
array(<span class="hljs-number">0</span>) {
}


  Dispatching a job <span class="hljs-string">'foo'</span>


Adding item <span class="hljs-string">'foo'</span> to queue


  Asserting the job <span class="hljs-string">'foo'</span> <span class="hljs-keyword">is</span> on the queue


Items in queue
array(<span class="hljs-number">1</span>) {
  [<span class="hljs-number">0</span>]<span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
  <span class="hljs-keyword">string</span>(<span class="hljs-number">3</span>) <span class="hljs-string">"foo"</span>
}


  Starting the workers


ENV<span class="hljs-operator">=</span>local TAG<span class="hljs-operator">=</span>latest DOCKER_REGISTRY<span class="hljs-operator">=</span>docker.io DOCKER_NAMESPACE<span class="hljs-operator">=</span>dofroscra APP_USER_NAME<span class="hljs-operator">=</span>application APP_GROUP_NAME<span class="hljs-operator">=</span>application docker<span class="hljs-operator">-</span>compose <span class="hljs-operator">-</span>p dofroscra_local <span class="hljs-operator">-</span><span class="hljs-operator">-</span>env<span class="hljs-operator">-</span>file ./.docker/.env <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.yml <span class="hljs-operator">-</span>f ./.docker/docker<span class="hljs-operator">-</span>compose<span class="hljs-operator">/</span>docker<span class="hljs-operator">-</span>compose.local.yml exec <span class="hljs-operator">-</span>T <span class="hljs-operator">-</span><span class="hljs-operator">-</span>user application php<span class="hljs-operator">-</span>worker supervisorctl start worker:<span class="hljs-operator">*</span>;
worker:worker_00: started
worker:worker_01: started
worker:worker_02: started
worker:worker_03: started


  Asserting the queue <span class="hljs-keyword">is</span> <span class="hljs-built_in">now</span> empty


Items in queue
array(<span class="hljs-number">0</span>) {
}


  Asserting the db <span class="hljs-built_in">now</span> contains the job <span class="hljs-string">'foo'</span>


Items in db
array(<span class="hljs-number">1</span>) {
  [<span class="hljs-number">0</span>]<span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span>
  <span class="hljs-keyword">string</span>(<span class="hljs-number">3</span>) <span class="hljs-string">"foo"</span>
}
</code></pre>
<p><a id="wrapping-up"> </a>
</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>Congratulations, you made it! If some things are not completely clear by now, don't hesitate to leave a comment. Apart from that, you should now have a running docker setup and the means to  "control" it conveniently via <code>make</code>.</p>
<p>In the next part of this tutorial, we will  <a target="_blank" href="https://www.pascallandau.com/blog/phpstorm-docker-xdebug-3-php-8-1-in-2022/">configure PhpStorm as our IDE to use the docker setup</a>.</p>
<p>Please subscribe to the <a target="_blank" href="https://www.pascallandau.com/feed.xml">RSS feed</a> or <a target="_blank" href="https://www.pascallandau.com/blog/#newsletter">via email</a> to get automatic notifications when this next part comes out :)</p>
]]></content:encoded></item></channel></rss>