How To Add Users To A Docker Container Without Interactive Prompts?

Published July 15, 2024

Problem: Adding Users to Docker Containers Non-Interactively

Adding users to Docker containers often needs interactive prompts. This can be inconvenient for automated processes or scripted deployments. It creates a challenge when trying to improve container management and user provisioning without manual input.

The Solution: Non-Interactive User Creation

Using useradd for Automated User Addition

The useradd command is a non-interactive option to adduser for creating users in Docker containers. This command lets you add users without manual input during the build process.

The basic syntax for useradd is:

useradd [options] username

Common options include:

  • -m: Create the user's home directory
  • -s: Specify the user's login shell
  • -u: Set a specific user ID
  • -g: Assign the user to a primary group

Tip: Secure User Creation

When creating users with useradd, consider using the -p option to set an encrypted password. This improves security by avoiding the use of default or empty passwords. For example:

useradd -m -s /bin/bash -p $(openssl passwd -1 "secure_password") username

Implementing the Solution in Dockerfile

To add users non-interactively in your Dockerfile, you can use the useradd command with options. Here's an example of how to add users in your Dockerfile:

RUN useradd -ms /bin/bash uwsgi
RUN useradd -ms /bin/bash celery

This creates two users, 'uwsgi' and 'celery', each with their own home directory and bash as their default shell.

To create a shared group for these users, you can use the groupadd command:

RUN groupadd worker
RUN usermod -aG worker uwsgi
RUN usermod -aG worker celery

These commands create a 'worker' group and add both 'uwsgi' and 'celery' users to it.