Getting started with Laravel and MongoDB in Docker for your next SAAS project

Adhikari Arpan
3 min readJul 8, 2020

tldr; scroll down to see the solution.

We recently started working on a SAAS product. After some consideration, we decided to go with MongoDB as the database and Laravel as the framework of choice.

To enable rapid develop-test-deploy cycle we’re containerizing the application. This also ensures our software runs in the same environment at every stage of it’s life-cycle and has an added benefit of being able to deploy it inside a Kubernetes Cluster if our service needs to scale.

Initially Alpine Linux was the flavour of choice but at the time of writing this article Alpine Linux does not have MongoDB drivers for PHP in it’s latest repository. They have the driver in their edge stream but that’s a no-go in my opinion.

So I decided to use Debian Linux and compile MongoDB driver from the source and then install the library.

Assumptions

  • You have initialized your Laravel application in the app directory.
  • You have Docker installed.

Solution

Below is the resulting Dockerfile for the container.

FROM httpd:2.4.43RUN  apt update && \
apt install -y php7.3-fpm \
php-gmp \
php-curl \
supervisor \
nano \
composer

#build mongodb php driver from source
RUN apt install -y git php-dev && \
cd /tmp && \
git clone https://github.com/mongodb/mongo-php-driver.git && \
cd mongo-php-driver && \
git submodule update --init && \
phpize && \
./configure && \
make all && \
make install

#add mongodb lib to php.ini
RUN echo "extension=mongodb.so" >> /etc/php/7.3/cli/conf.d/20-mongodb.ini
#copy the app
WORKDIR /app
COPY app /app
CMD ["php","-S","0.0.0.0:80","-t","public"]

This is not the cleanest approach since all the build tools and utilities remain in the container. Ideally, we want to build and export the artifacts to another cleaner container but this gets the job done so we can start building the actual software ASAP.

To start the container, run the following command from your project directory. ( If you’re in Windows, run the command in Power-shell without the sudo prefix and use ‘\’ instead of ‘/’ for directory url.)

sudo docker build -t app . && sudo docker run -p "0.0.0.0:80:80" --mount type=bind,source="$(pwd)/app",target=/app app

The line of code above mounts your local app directory as a volume inside your container so you can test your app without restarting it every time.

Finally, install the php-mongodb library for Laravel.

sudo docker exec -it $(sudo docker ps -lq) composer require jenssegers/mongodb

This effectively updates the composer.json in your project’s directory so you don’t have to worry about running the composer require outside of your container again.

Final thoughts

There are still few improvements to be made on this setup. The original goal was to be able to start developing ASAP and this accomplishes that pretty well.

The build code was adopted from the php official site.

--

--