Lab 2_ Building and Running a Custom Docker Image
Lab 2_ Building and Running a Custom Docker Image
Objective
This lab demonstrates how to create a custom Docker image using a Dockerfile, build the
image, and run it as a container. By completing this lab, you will understand:
Pre-requisites
mkdir rick-docker
cd rick-docker
Explanation: The folder acts as a workspace to store your Dockerfile and related files.
Step 2: Write a Simple Python Script
Open the file in a text editor and paste the following code (For example, you can use notepad.
See the video for detailed instructions.):
2. Save and close the file (Be sure to save as a .py file and not .txt)
Explanation:
○ This script is a simple Python program that prints a message. The script will be
executed inside the Docker container.
A Dockerfile is a simple text file that contains a series of instructions used to create a Docker
image. It's like a recipe for building a containerized application. It tells Docker how to set up an
environment (such as installing software, setting up configurations, or copying files) for your
application so it can run in a Docker container.
1. In the same folder (rick-docker), create a file named Dockerfile (no extension).
Open the file in a text editor and add the following content:
Explanation:
○ FROM: Specifies the base image to use (Python 3.9 slim version).
○ COPY: Copies the app.py file from your local system into the container at
/app/app.py.
○ WORKDIR: Sets the working directory for any subsequent commands in the
Dockerfile.
○ CMD: Specifies the command to run when the container starts (python
app.py).
1. Open a terminal in the rick-docker folder. (InWindows use cmd, and cd to navigate to
the correct folder)
2. Explanation:
○ docker build: Command to build a Docker image.
○ -t my-python-app: Tags the image with the name my-python-app.
○ .: Refers to the current directory where the Dockerfile is located.
Expected Output:
1. Explanation:
○ docker run: Creates and starts a container from the image.
○ my-python-app: Refers to the custom image you just built.
Expected Output:
Hello from Docker!
docker images
1. Explanation:
○ docker images: Displays all locally built or pulled images.
Expected Output:
REPOSITORY TAG IMAGE ID CREATED SIZE
my-python-app latest <image-id> A few seconds ago <size>
Step 7: Clean Up
docker ps -a
docker rm <CONTAINER ID>
Conclusion