Symfony is a very popular PHP framework used to create websites and web applications. In this article we will set up a basic development environment using Docker containers. The advantage of using a Docker container for this environment is that you can target specific PHP versions, middleware and databases without having to manage conflicting versions on your computer.
Step 1: Create a Docker image to bootstrap new Symfony projects.
The purpose of this image is to provide a minimal environment for creating new Symfony projects using the symfony new command.
First create a new directory:
> mkdir ~/work/src/symfony_setup
Create a new file in the symfony_setup directory called Dockerfile. Enter the following contents in the Dockerfile:
FROM php:5-fpm-alpine RUN curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony RUN chmod a+x /usr/local/bin/symfony WORKDIR /root/work/src
From the symfony_setup directory, enter the following command:
> docker build -t symfony_setup .
This command will build an image called symfony_setup that you can use anytime you want to create a new Symfony project. To do so use the command:
> docker run --rm -v ~/work/src:/root/work/src symfony_setup symfony new proj_new
Be sure to replace proj_new with the desired name for your project. You should also make sure that you have created a directory at ~/work/src before executing this command.
Step 2: Create a docker image to run a Symfony project
You will need to add two settings to the php.ini configuration file. To do this, create a new directory:
> mdkir ~/work/src/symfony_run
Create a new file in the symfony_run directory called Dockerfile. Enter the following contents in the Dockerfile:
FROM php:5-fpm-alpine RUN curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony RUN chmod a+x /usr/local/bin/symfony COPY php.ini /usr/local/etc/php/php.ini WORKDIR /root/work/src/proj_new EXPOSE 8000 CMD php bin/console server:run 0.0.0.0:8000
You should use the same project name instead of proj_new as you did in Step 1 for the WORKDIR line of this Dockerfile.
You will also notice that we are copying a php.ini into our container. This is so that we can provide the following arguments to the PHP environment:
date.timezone = "Europe/Amsterdam"
Copy your php.ini.default to the same directory as the Dockerfile and ensure that the above directives are set.
Note: You should use the appropriate timezone code for your locale. Refer to this link for more details.
Now you can build this image using the command:
> docker build -t my-symfony .
Once the image is built, you can run it with the command:
> docker run -d -p 8000:8000 -v ~/work/src:/root/work/src my-symfony
This command will start up a container, mapping to the local directory on your machine where the project source was created in step 1.
Open a web browser to http://localhost:8000 to view your newly created and initialized Symfony application!