how to create a non root user to access SSH commands with Docker

Viewed 276

I have an application that gets deployed from a docker image to a Kubernetes pod. Inside of my docker image I run the following command

FROM openjdk:17.0.1-slim

USER root

WORKDIR /opt/app
ARG JAR_FILE
ARG INFO_APP_BUILD

RUN apt-get update
RUN apt-get install -y sshpass
RUN apt-get install -y openssh-service

COPY /build/libs/*SNAPSHOT.jar /opt/app/app.jar
ENV INFO_APP_BUILD=${INFO_APP_BUILD}

EXPOSE 8080

CMD java -jar /opt/app/app.jar

When the application gets deployed, out of my control, the user gets set to a non root user.

Now the important part is that when i try to launch an ssh command i get an error message no user exists for uid [random id here]

My goal is to configure the docker image to create a user and grant it permission to use the SSH command.

1 Answers

When the application gets deployed, out of my control, the user gets set to a non root user.

Inside the container, the user running java -jar /opt/app/app.jar is root, because of USER root.

Outside the container, on the host, a deployed application is usually (almost exclusively) never executed/accessed as root.

But it should still make ssh request from within the container to a server:

  • the openssh service is started
  • the container /root/.ssh has the right public/private key
  • the ~user/.ssh folder, on the target server where the Docker application is running, has the authorized_keys with the public one in it.

But if the user does not exist inside the container, you need to create it on docker run, as in here:

docker run -it --rm --entrypoint sh "$@" \
-c "[ -x /usr/sbin/useradd ] && useradd -m -u $(id -u) u1 -s /bin/sh || adduser -D -u $(id -u) u1 -s /bin/sh;
exec su - u1"
Related