In this article, we will see how to build and run a docker container from the Dockerfile.
Let’s write an example Dockerfile which contains the instructions on how to build the Docker image.
# Use an official Python runtime as a parent image
# Set the working directory to /app
# Copy the current directory contents into the container at /app
COPY . /app
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Make port 80 available to the world outside this container
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
The above Dockerfile starts by setting an official Python 3.7 image, sets the working directory to /app, copies the current directory into the container, installs the packages specified in requirements.txt, exposes port 80, sets an environment variable, and finally runs app.py when the container launches.
Building the docker image
docker build command to build the docker image. This command takes the path of the Dockerfile as an argument and builds the Docker image based on the instructions specified in the Dockerfile.
docker build -t my-flask-app .
The -t option in the above command tells about the name of the docker image and “.” indicates the location of the docker file which is nothing but the current directory.
Run the Docker container
Once the Docker image is built, we can use the
docker run command to create and run the Docker container from the Docker image. Following is the command to run the docker container.
docker run -p 4000:80 my-flask-app
In the above command,
-p specifies the port mapping i.e. port 4000 on the host machine is mapped to port 80 in the container and
my-flask-app is the name of the Docker image.