How to write a Dockerfile

Documentation on How to write a Dockerfile

Follow @donadoio

How to write a Dockerfile

A Dockerfile is a text document (without a file extension) that contains the instructions to set up an environment for a Docker container. You can build a Docker image using a Dockerfile.

The command docker build . builds a Docker image using the Dockerfile in the directory that this command is executed.

Here is an example of a docker file:

# Using official ubuntu image as a parent image
FROM ubuntu:latest

# Setting the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Getting the updates for Ubuntu and installing python into our environment
RUN apt-get -y update  && apt-get install -y python

# Run app.py when the container launches
CMD ["python", "app.py"]

The Dockerfile is explained line by line below:

# Using official ubuntu image as a parent image
FROM ubuntu:latest

Most docker files start from a ‘parent’ image. The parent image is added through the FROM keyword. Your image builds upon the parent image. We add the official Ubuntu image using FROM ubuntu:latest.

# Setting the working directory to /app
WORKDIR /app

You then set the working directory in your container with WORKDIR. WORKDIR /app sets the current directory to /app when the container starts running.

# Copy the current directory contents into the container at /app
COPY . /app

So far, we have the Ubuntu OS in our environment with the current directory set to /app. Now we want to transfer our own files into the container from the outside. We do this using COPY . /app where the COPY command copies all the files from our current directory (the one which contains the Dockerfile) into the /app. Our container will now contain the Ubuntu OS and the files from our local directory with the working directory set to ./app. That’s it! The container will only have the things you specify it to have.

# Getting the updates for Ubuntu and installing python into our environment
RUN apt-get -y update  && apt-get install -y python

The RUN command executes when we build the image and any additional dependencies or packages are usually installed using the RUN command. We assume that we have the OS image we specified and build other packages on top of it.

# Run app.py when the container launches
CMD ["python", "app.py"]

The CMD specifies the command which is executed when we start the container.

Note: You can insert comments in your Dockerfile using #.

Back to Docker for ft_server