Containerizing your Python project with Docker offers a seamless and consistent development environment. In this section, we'll cover how to wrap your Python package in a Docker container, install it natively within the container, and use Jupyter Lab for interactive testing and experimentation.
Let's start by creating a Dockerfile in the root of your project. This file defines the environment and commands to build your Docker image.
touch Dockerfile
In this context, the naming Dockerfile
is mandatory for the docker runner, otherwise further parameters
might be needed.
Start with a base image that includes Python. For example
FROM python:3.8-slim
Copy your requirements file and install the dependencies:
COPY requirements.txt /tmp/
RUN pip install -r /tmp/requirements.txt
Copy your project files into the container and install your package:
COPY . /app/
WORKDIR /app
RUN pip install -e .
(Optional) Set Up Jupyter Lab: If you want to include Jupyter Lab for interactive testing:
RUN pip install jupyterlab
CMD ["jupyter", "lab", " - ip=0.0.0.0", " - allow-root", " - no-browser"]
docker build -t tutorial-project .
Additional commands:
> docker ps -a
> docker images
docker run -p 8888:8888 tutorial-project
If you've set up Jupyter Lab, it will be accessible at http://localhost:8888. The terminal output will provide a token to log in. The usage of docker will guarantee yoy, feature such as
- Consistency: Docker ensures that your project runs in the same environment, regardless of where it's deployed, reducing the "it works on my machine" problem.
- Isolation: Running your project in a container isolates it from the host system, minimising conflicts between different projects' dependencies.
- Reproducible: Docker containers can be shared and run by other team members or in production environments, ensuring everyone is working with the same setup.
By containerisation your Python project with Docker, you create a consistent, isolated, and reproducible development environment. Incorporating tools like Jupyter Lab within your Docker setup further enhances the development experience, providing a powerful platform for interactive testing and exploration.