如何在 USER 指令后在 CMD Dockerfile 指令中启动服务

问题描述 投票:0回答:1

我想运行一个容器:

  1. 默认有非 root 用户运行它(USER Dockerfile 指令)
  2. 作为 crontab 运行系统服务(CMD Dockerfile 指令)

人们能想到的最简单的事情就是执行以下 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"]

显然,CMD指令会返回错误,因为cron服务需要由root运行。怎么解决这个问题?

docker cron dockerfile containers
1个回答
0
投票

你可以这样实现:Dockerfile 和startup.sh

Dockerfile

FROM openjdk:8

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

# 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"]


启动.sh

#!/bin/bash

# Start the cron service
service cron start

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

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

© www.soinside.com 2019 - 2024. All rights reserved.