How to start a service in CMD Dockerfile instruction after a USER instruction

36 Views Asked by At

I want to run a container which:

  1. Has a non-root user running it by default (USER Dockerfile instruction)
  2. Runs a system service (CMD Dockerfile instruction) as crontab

The simplest thing one can think to is to execute the following Dockerfile:

FROM openjdk:8
RUN apt-get update && apt-get -y install nano
RUN apt-get update && apt-get -y install cron
RUN useradd -u 8877 dockeras
RUN mkdir /home/dockeras
RUN chown -R dockeras /home/dockeras && chmod -R u+rwx /home/dockeras
USER dockeras
CMD ["cron", "-f"]

Obviously, the CMD instruction will return an error because the cron service requires to be run by root. How to solve this?

1

There are 1 best solutions below

7
dincer.unal On

You could implement it like this: Dockerfile and startup.sh

Dockerfile

FROM openjdk:8

# Install necessary packages
RUN apt-get update && \
    apt-get -y install nano cron sudo

# Create a non-root user
RUN useradd -u 8877 dockeras && \
    mkdir /home/dockeras && \
    chown -R dockeras /home/dockeras && \
    chmod -R u+rwx /home/dockeras

# Copy the startup script
COPY startup.sh /home/dockeras/startup.sh

# Set the script as executable
RUN chmod +x /home/dockeras/startup.sh

# Switch to the non-root user
USER dockeras

# Set the entry point to the startup script
ENTRYPOINT ["/home/dockeras/startup.sh"]


startup.sh


#!/bin/bash

# Start cron with sudo
sudo service cron start

# Run your application service here
# Example:
# java -jar /path/to/your/application.jar

# Keep the container running
tail -f /dev/null