Practice Exercise 2: Docker Container Management
Objective
In this lab exercise, you will learn how to create Docker images using Dockerfiles and how to start, stop, and modify an application container.
Prerequisites
- Access to your instance with Docker installed.Follow the steps in Lab Environment to access your machine.
- Basic familiarity with Linux command line.
Duration: 60 minutes
Tasks
Part 1: Creating Docker Images Using Dockerfiles
Task 1. Create a directory for your Docker project:
mkdir docker_lab
cd docker_lab
Task 2. Inside the docker_lab
directory, create a Dockerfile for a simple web application. You can use a basic Python Flask application as an example.
# Use an official Python runtime as a parent image
FROM python:3.12
# Set the working directory inside the container
WORKDIR /app
# Copy the requirements file into the container
COPY requirements.txt requirements.txt
# Install the required packages
RUN pip install -r requirements.txt
# Copy the current directory contents into the container at /app
COPY . /app
# Expose port 5000
EXPOSE 5000
# Command to run the Flask application
CMD ["python", "app.py"]
Task 3. Create an app.py
file and a requirements.txt
file in the same directory with some simple Python code and dependencies.
See sample `app.py` and `requirement.txt` file below:
#app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
#requirements.txt
Flask==2.1.1
Werkzeug==2.2.2
Task 4. Build the Docker image using the Dockerfile:
docker build -t mywebapp .
Task 5. Verify that the image has been created successfully:
docker images
Part 2: Starting, Stopping, and Modifying an Application Container
-
Start a container from the image you created:
docker run -d -p 5000:80 mywebapp
-
Check if the container is running:
docker ps
-
Access the web application from your IP address and port 5000 in a web browser.
-
Stop the container:
docker stop <container_id>
-
Modify the app.py file or any other files as desired.
-
Build a new version of the image with the changes:
docker build -t mywebapp .
-
Start a new container from the updated image.
- Verify that the changes are reflected in the web application.
Conclusion
In this lab exercise, you learned how to create Docker images using Dockerfiles and how to manage Docker containers. You also practiced making modifications to the application and updating the Docker image. These skills are essential for working with Docker and containerized applications.
Remember to clean up your resources by stopping and removing any running containers and deleting unused images when you're done.