Skip to content

Write Your First Dockerfile

View the Full Course Now

Your first Dockerfile Step by Step

Let's create this Dockerfile:

FROM php:7.2-cli

RUN mkdir /myproject
COPY index.php /myproject
WORKDIR /myproject
CMD php index.php

It take a "php:7.2-cli" base image, and then adds a few things on top:

  • makes a new directory /myproject"
  • copies index.php into /myproject
  • makes the workdir /myproject, meaning, the container will start in this directory (like cd /myproject)
  • when the container starts it will run php index.php

And also this index.php file in the same directory:

<?php

echo "hello world \n\n";

Now go into the folder where the Dockerfile is located at. And open in a terminal type:

docker build -t myphpapp .

But what does it do?

  • build builds a new image
  • -t is a tagging. In this case "myphpapp", so you can later find it.
  • . is telling Docker what is the "build context". Meaning, in the Dockerfile you wrote COPY index.php /myproject, that means it knows to look in this folder when searching for this index.php file

Then run the container:

docker run --name myphpapp myphpapp
  • Should print out "hello world" with two line breaks
  • Ends the container immediately, the process "php index.php" has finished
  • "CMD php index.php" opens this upon spin up of the container
  • Give the container a name called "myphpapp"
docker image ls
  • List all the images
  • See on top your newly created image
docker ps -a
  • List the containers
docker rm myphpapp
  • Remove the container
docker rmi myphpapp
  • rm i will delete an image
  • And all depending images if they are not necessary anymore