Create Docker Container for a simple PHP program

Create project directory

We are going to create a simple php program, so create a project folder or directory as simplephp

mkdir simplephp
cd simplephp

Create simple php program file

Now create a php file as index.php inside the folder simplephp and add the below code. On running the code it will print the string "I am running inside docker container!"

<?php
 echo "I am running inside docker container!";
?>

Docker setup

Below steps need to follow to setup and run docker container:

  1. Docker installation (if not already installed)
  2. Create Dockerfile
  3. Create docker image
  4. Create container
  5. Run docker container

Docker Installation

Install docker desktop from here for Windows and Mac OS and for Linux install it from here.

Create a Docker file

A docker file is needed to automate the process of building a Docker image. It contains a set of instructions that define how a containerized application should be set up, including which base image to use, what files to copy, which environment variables to set, and the commands to run when the container starts.

Inside the folder simplephp create a file called Dockerfile . Please note that the file should not have any extension. Write the below script/commands in the Dockerfile.

# Use the official PHP image from Docker Hub
FROM php:8.1-apache

# Copy your PHP file into the Apache server directory
COPY index.php /var/www/html/

# Expose port 80 to allow access to the container from the host
EXPOSE 80

Create a docker image

Run the below command inside the folder. Do not forget to add a dot ‘.’ at the end

docker build -t simplephp-image.

To check docker image run the command docker images :

C:\DockerProjects\simplephp>docker images
REPOSITORY        TAG       IMAGE ID       CREATED         SIZE
simplephp-image   latest    ef4186497757   2 minutes ago   500MB

Note: If you face a connection error something like below then you have not started docker:
ERROR: error during connect: Head "http://%2F%2F.%2Fpipe%2FdockerDesktopLinuxEngine/_ping": open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified.

So start docker desktop for WINDOWS and MAC and run sudo systemctl start docker in linux

Create and run docker container

Run the below command to create container from the image and run it at 80 which was set in the Dockerfile. This port 80 is a port inside the docker. To access the application outside docker, e.g. from a browser we need to bind a port (5000) in the local machine with the port 80.

docker run -p 5000:80 simplephp-image

In the browser hit the url http://localhost:5000

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *