Php connect to mongodb docker

We can containerize our applications using Docker to have a separate installation of the required packages with the application-specific versions independent of the underlying operating system. We can use Docker Containers to make our application portable so that we can simply move it to another system having docker. This tutorial provides all the steps to containerize a PHP application using Apache Web Server as the webserver and either MySQL or MongoDB as the database server.

Prerequisites

Windows -  How To Install WSL 2 [Windows Subsystem for Linux] with Ubuntu On Windows 10 and How To Install Docker Desktop On Windows 10. Optionally you may follow How To Change Docker Data Path On Windows 10.

Ubuntu - How To Install Docker Engine on Ubuntu 20.04 LTS

macOS - How To Install Docker Desktop On Mac

Install PHP and Apache Web Server

Create a directory to store your project-specific files. I have created the directory helloworld to store all the project files. Now create the file docker-compose.yml at the root of your project directory as shown below.

# docker-compose.yml
version: "3.8"
services:
apache:
container_name: apache
build: ./docker/apache
links:
- php
ports:
- "80:80"
volumes:
- ./src:/usr/local/apache2/htdocs
php:
container_name: php
build: ./docker/php
ports:
- "9000:9000"
volumes:
- ./src:/usr/local/apache2/htdocs
working_dir: /usr/local/apache2/htdocs

Now create the directories - docker and src within the project root directory. Also, create two directories within the docker directory i.e. php and apache.

Create the Dockerfile within the PHP directory as shown below.

# docker/php/Dockerfile
FROM php:8.1-fpm

Create the Dockerfile within the Apache directory as shown below.

# docker/apache/Dockerfile
FROM httpd:2.4.51

Create the index.php file within the src directory as shown below.

# src/index.php

Chủ Đề