How to build docker with non-root user privileges to setup python application with pipenv?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Building Docker containers with non-root user privileges can enhance security, especially when deploying Python applications. By minimizing the risk associated with running applications as the root user inside a container, you can reduce potential vulnerabilities. This article provides a detailed guide on setting up a Python application using Pipenv within a Docker container, avoiding root privileges.
Overview of Docker Security Practices
Docker containers commonly run processes as root by default. While this simplifies many tasks, it can lead to security vulnerabilities, especially if an attacker gains access to the container. Running applications as a non-root user is a best practice to mitigate these risks. Additionally, it's essential to ensure that the non-root user can install and manage Python dependencies through Pipenv without requiring elevated permissions.
Prerequisites
- Familiarity with Docker and Docker commands.
- Basic understanding of Python and Pipenv.
- Docker installed on your machine.
Setting Up a Dockerfile for a Non-Root User
You will create a Dockerfile for your Python application that uses Pipenv to manage dependencies. Instead of using the default root user, we will create a non-root user called `app`.
Step 1: Initialize the Python Application with Pipenv
First, create a Python application. Use Pipenv to initialize the environment and install any required dependencies.
- Base Image: We use `python:3.10-slim` for a lightweight image.
- System Dependencies: System packages like `gcc` and `libpq-dev` are necessary for building Python packages with C extensions.
- Non-Root User: We add a user named `app` and switch to this user for installing application dependencies and running the app.
- Application Directory: The application directory `/app` is set, ownership assigned to the `app` user.
- Pipenv: Installed in the user's local directory to avoid permission issues.
- Copy Files and Set Ownership: Files are copied with ownership specified for the app user to ensure read/write permissions.
- Permission Denied: This may occur if ownership is improperly set for files in the container. Ensure your files are owned by the app user.
- Pipenv Issues: Verify that Pipenv is installed under the correct environment by invoking `which pipenv` inside the container.
- Regularly update the base image.
- Scan images for vulnerabilities using tools such as Docker Bench Security.
- Limit container memory and CPU usage.

