Prepare a simple Docker Compose project with a build context
In this step, we will prepare a simple Docker Compose project that includes a build context. A build context is the set of files at a specified location (PATH or URL) that are sent to the Docker daemon to build a Docker image. This is important because the Dockerfile and any files it needs (like application code) must be within the build context.
First, let's create a directory for our project. We will name it my-watch-app
.
mkdir ~/project/my-watch-app
cd ~/project/my-watch-app
Now, we need to create a simple application file. We will use a basic Python script that prints a message.
nano app.py
Add the following content to app.py
:
print("Hello from the Docker container!")
Save and close the file (Ctrl+X, Y, Enter).
Next, we need to create a Dockerfile that will build an image for our application. The Dockerfile will copy our Python script into the image and then run it.
nano Dockerfile
Add the following content to the Dockerfile:
FROM python:3.9-slim
WORKDIR /app
COPY app.py .
CMD ["python", "app.py"]
This Dockerfile uses a slim Python 3.9 image as the base, sets the working directory to /app
, copies app.py
into the /app
directory, and finally sets the command to run the Python script when the container starts.
Finally, we need to create a docker-compose.yaml
file to define our service. This file will tell Docker Compose how to build and run our application.
nano docker-compose.yaml
Add the following content to docker-compose.yaml
:
version: "3.8"
services:
myapp:
build: .
volumes:
- .:/app
This docker-compose.yaml
file defines a service named myapp
. The build: .
instruction tells Docker Compose to build the image using the Dockerfile in the current directory (which is our build context). The volumes: - .:/app
line mounts the current directory (.
) on the host machine to the /app
directory inside the container. This is crucial for docker compose watch
as it allows changes on the host to be reflected in the container.
Now, let's build and run our service using Docker Compose to ensure everything is set up correctly. Since Docker Compose is not pre-installed, we need to install it first.
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
Now we can use docker-compose
.
docker-compose up --build
You should see output indicating that the image is being built and the container is running, printing "Hello from the Docker container!". Press Ctrl+C
to stop the container.