Docker stack - wait for it - java

I would like to start two services in a stack.
Mysql
Spring boot app
The main problem is that spring boot starts before database (or starts when connection to database is not allowed). Then in logs I could see: java.net.UnknownHostException: database.
We could use startup order:
https://docs.docker.com/compose/startup-order/
So what I do? I copy wait-for-it.sh to file with docker-compose, add line
command: ["./wait-for-it.sh", "database:3306", "--", "java -Dspring.profiles.active=prod -jar app.jar"]
The result is:
java.lang.IllegalArgumentException: Invalid argument syntax: --
My entrypoint in backend Dockerfile:
ENTRYPOINT ["java","-Dspring.profiles.active=prod", "-jar","app.jar"]
How to make that spring boot app will wait for MySQL database under docker stack?

When you run the container, the ENTRYPOINT and CMD are combined. In your example you've set ENTRYPOINT to run the Java process, but then override CMD in the docker-compose.yml: instead of actually running the wait-for-it.sh script, it just gets passed as extra parameters to the JVM.
A typical pattern for using both of these together is to have ENTRYPOINT be some sort of wrapper that does first-time setup, then takes CMD as additional parameters. For this to work CMD needs to be a complete shell command. Change the Dockerfile to look like:
COPY wait-for-it.sh entrypoint.sh .
# ENTRYPOINT _must_ be in JSON-array form
ENTRYPOINT ["./entrypoint.sh"]
# CMD may be either string or JSON-array form
# (This is exactly what you originally had as ENTRYPOINT)
CMD ["java", "-Dspring.profiles.active=prod", "-jar", "app.jar"]
The entrypoint script can be very simple:
#!/bin/sh
# Wait for the database to be up
if [ -n "$MYSQL_HOST" ]; then
./wait-for-it.sh "$MYSQL_HOST:3306"
fi
# Run the CMD
exec "$#"
The important detail here is that I've configured the database host to be passed as an environment variable. This requires a shell to run to expand it, which is tricky to do in the JSON-array ENTRYPOINT syntax, so I've moved it into a separate script.
Finally, in the docker-compose.yml, do not override command: (or entrypoint:), but do make sure to set the environment variable for the script to be able to find the database.
version: '3.8'
services:
database: { ... }
application:
environment:
MYSQL_HOST: database
depends_on:
- database
# no command: override
The wrapper here will run whenever the container starts up, so if you docker-compose run application bash to get an interactive shell based on the image, it will still wait for the database to be up.
If you control both the Dockerfile and the docker-compose.yml, you shouldn't usually need to override command: in the Compose settings. I find the entrypoint-wrapper pattern useful enough that I generally default to using CMD in my Dockerfiles (there is no requirement to have an ENTRYPOINT).

Related

gitlab-runner passes wrong arguments to custom image

I have written a small CLI using Java, Argparse4j, and packaged it in docker using this Dockerfile:
FROM openjdk:18
ENV JAR_NAME "my-jar-with-dependencies.jar"
ENV PROJECT_HOME /opt/app
RUN mkdir -p $PROJECT_HOME
WORKDIR $PROJECT_HOME
COPY run.sh $PROJECT_HOME/run.sh
RUN chmod +x $PROJECT_HOME/run.sh
COPY target/$JAR_NAME $PROJECT_HOME/cli.jar
ENTRYPOINT ["./run.sh"]
The last line of the Dockerfile then invokes a simple bash script:
#!/bin/bash
java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar ./cli.jar "$#"
The CLI I wrote has three main actions: upload, download and apply. Therefore argparse4j expects one of these actions to be passed as the first parameter, i.e.
java -jar cli.jar download #... whatever other argument
This works just fine when running the docker image locally, but completely fails when running in the CI pipeline:
download:
stage: download
image: <url>/my-image:<tag>
variables:
URL: <URL>
API_KEY: <API_KEY>
CI_DEBUG_TRACE: "true"
script:
- download -f zip -u true test-download.zip
This is the error that is returned:
Executing "step_script" stage of the job script 00:01
Using docker image sha256:<sha> for <url>/my-image:<tag> with digest <url>/my-image:<tag>#sha256:<sha> ...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
usage: tool [-h] ACTION ...
tool: error: invalid choice: 'sh' (choose from 'upload', 'download',
'apply')
I have tried following the suggestion in gitlab-runner doesn't run ENTRYPOINT scripts in Dockerfile but I can't seem to get the CI part to work correctly.
I would like to avoid using the entrypoint directive as it needs to be used on multiple files, so I rather fix the issue at the root.
Does anyone have an idea of what is happening or how to fix it?
I would like to avoid using the entrypoint directive as it needs to be used on multiple files, so I rather fix the issue at the root.
You can change your Dockerfile instead to keep default ENTRYPOINT (as openjdk:18 doesn't define any entrypoint, it will be empty):
FROM openjdk:18
# ...
# ENTRYPOINT ["./run.sh"] # remove this
# Add run.sh to path to be able to use `run.sh` from any directory
ENV PATH="${PATH}:/opt/app"
And update your run.sh to specify full path to jar:
#!/bin/bash
java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar $PROJECT_HOME/cli.jar "$#"
Now your container will start in Gitlab without having to specify entrypoint keyword for job. You can then setup something like this:
download:
stage: download
image: <url>/my-image:<tag>
variables:
URL: <URL>
API_KEY: <API_KEY>
CI_DEBUG_TRACE: "true"
script:
# Specify command using run.sh
# This command is run from within your container
# Note that script is not an argument passed on your image startup
# But independent commands run within your container using shell
- run.sh download -f zip -u true test-download.zip
Notes:
Gitlab won't run your script in Dockerfile's WORKDIR but in a dedicated directory where your project will be cloned.. Using ./ will look for script and jar in current directory at the moment your command is run, but they wouldn't be found if not run from /opt/app. Specyfing full path to jar and adding your run.sh script to PATH make sure they'll be found wherever your run.sh from. Alternatively you could run cd /opt/app in your job's script but it may cause unwanted side effects.
Without ENTRYPOINT you won't be able to run Docker commands like this
docker run " <url>/my-image:<tag>" download ...
You'll need to specify either COMMAND or --entrypoint such as
docker run "<url>/my-image:<tag>" run.sh download ...
docker run --entrypoint run.sh "<url>/my-image:<tag>" download ...
You specified not wanting to do this, but overriding image entrypoint on your job seems a much simpler and straightforward solution. Using multiple files you may leverage Gitlab's extends and include.
And now for the fun part
what is happening
When Gitlab run your container for a job it will use the entrypoint defined in your Dockerfile by default. From doc:
The runner starts a Docker container using the defined entrypoint. The default from Dockerfile that may be overridden in the
.gitlab-ci.yml file.
The runner attaches itself to a running container.
The runner prepares a script (the combination of before_script, script, and after_script).
The runner sends the script to the container’s shell stdin and receives the output.
And what the doc doesn't say is that Gitlab will try to use various form of sh as Docker command. In short for step 1. it's like running this Docker command:
# Gitlab tries to run container for your job
docker run -it "<url>/my-image:<tag>" sh
It doesn't work as Gitlab will use default entrypoint and the final command run in Docker is:
./run.sh sh
Where ./run.sh is the entrypoint from Dockerfile and sh is the command provided by Gitlab. It causes the error you see:
tool: error: invalid choice: 'sh' (choose from 'upload', 'download', 'apply')
You never reach your job's script (step 4). See ENTRYPOINT vs. CMD for details.
Furthermore, the script you define is a command itself. Even if your container started, it wouldn't work as the following command would be run inside your container:
download -f zip -u true test-download.zip
# 'download' command doesn't exists
# You probably want to run instead something like:
/opt/app/run.sh download -f zip -u true test-download.zip
So, after a bit of research, I have been able to find a solution that works for me.
From my research (and as Pierre B. pointed out in his answer), Gitlab essentially tries to inject a shell script that performs a check for which shell is available.
Now, my solution is in no way elegant, but does achieve what I wanted. I modified the Dockerfile like so:
FROM openjdk:18-bullseye
ENV JAR_NAME "my-jar.jar"
ENV PROJECT_HOME /opt/app
RUN mkdir -p $PROJECT_HOME
WORKDIR $PROJECT_HOME
COPY run.sh $PROJECT_HOME/run.sh
RUN chmod +x $PROJECT_HOME/run.sh
COPY target/$JAR_NAME $PROJECT_HOME/cli.jar
RUN echo '#!/bin/bash \njava $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar $PROJECT_HOME/cli.jar "$#"' > /usr/bin/i18n && \
chmod +x /usr/bin/i18n
ENTRYPOINT ["./run.sh"]
And also modified the run.sh script this way:
#!/bin/bash
if [[ -n "$CI" ]]; then
echo "this block will only execute in a CI environment"
exec /bin/bash
else
echo "Not in CI. Running the image normally"
java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar ./cli.jar "$#"
fi
This works because Gitlab, in its list of predefined variables, provides a CI env var that is set when the script is running on the CI. By doing so, I skip the java invocation but leave it in the case I need to use it when not on a CI.
Now when I need to use my image, all I need to specify in my .gitlab-ci.yml file is this:
download:
stage: download
image: <url>/my-image:<tag>
variables:
URL: <URL>
API_KEY: <API_KEY>
CI_DEBUG_TRACE: "true"
script:
- i18n download -f zip -u true test-download.zip # This calls the script that was injected in the Dockerfile
This way I essentially mimic an actual CLI, and can use it in all my projects that require this tool.
I am not sure though why I need to "echo" the script for the CLI, and I can't simply copy it. For some reason the env variables are not passed down and I couldn't spend any more time debugging it. So for now, it will stay like this.
If you have any recommendations on how to clean this up, please leave some comments and I will edit my answer!
Try to wrap your script in single quotes:
script:
- 'download -f zip -u true test-download.zip'
EDIT:
Oh, this open bug in gitlab could be relevant to you

Install a custom package in a docker container that keeps exiting

I have a docker container which runs a springboot java application. Dockerfile:
# Create container with java preinstalled
FROM openjdk:8-jdk-alpine
# Create app directory
VOLUME /tmp
# Handle Arguments
ARG JAR_FILE
ARG ENV_NAME
ENV SPRING_PROFILES_ACTIVE=${ENV_NAME}
RUN echo ${ENV_NAME}
# Bundle app source
COPY ${JAR_FILE} app.jar
COPY application.yml application.yml
# Run the server
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-Dspring.config.location=application.yml","-jar","app.jar"]
Now, I have a custom library I need to install in that container. I'll need to copy the installation, extract it, run the install script and answer prompts (Y/n)
I understood the easiest way to do this is to connect to the container, install the package and commit the changes.
First - I start the container using:
docker run --name local-jdk8 -d openjdk:8-jdk-alpine
The next step is to copy the data and run the install script, but the container keeps on exiting since the run command is empty ("/bin/sh") which means I can't run
docker exec -it local-jdk8 bash
Any ideas on how I can modify such a container?
Solved it using expect library
My dockerfile :
# Create container with java preinstalled
FROM openjdk:8
# Create app directory
VOLUME /tmp
# Handle Arguments
ARG JAR_FILE
ARG ENV_NAME
ARG DRIVER_FILE
# Environment
ENV SPRING_PROFILES_ACTIVE=${ENV_NAME}
RUN echo ${ENV_NAME}
# Fingerprint Driver
RUN apt-get update -y
RUN apt-get install -y expect
COPY ${DRIVER_FILE} driver.tar.gz
COPY driver-install.exp driver-install.exp
RUN tar -xzf driver.tar.gz
RUN /driver-install.exp
# Copy app source
COPY ${JAR_FILE} app.jar
COPY application.yml application.yml
# Run the server
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-Dspring.config.location=application.yml","-jar","app.jar"]
driver-install.exp is the expect scripts that automatically interacts with the package installation
For what it's worth, here is a little trick that allows you to keep your container running to modify and commit it:
docker run --name local-jdk8 -d openjdk:8-jdk-alpine tail -f /dev/null
Furthermore, there is no bash installed on the container so sh will have to do:
docker exec -it local-jdk8 sh
Nevertheless, modifying Dockerfile is the better approach, since your change is persisted in code, rather than done on an potentially ephemeral container.

Docker container hostname

I'm trying to set docker container hostname (HOSTNAME env var) during startup, this is .sh script specified in ENTRYPOINT of dockerfile:
#!/bin/sh
export HOSTNAME=something-$(hostname)
java $JAVA_OPTS -jar /app.jar
I want this new hostname to be seen for jvm.
All I get is standard docker hostname like that:
/ # env
HOSTNAME=04dbf311a3be
When i set the hostname manually using this export above after the container is started everything works just fine. Everything is being run in swarm using compose stackfile.
EDIT1:
I am not doing this during container build but during startup
EDIT2:
To be clear, what i have:
DOCKER SWARM:
CONTAINER1
HOSTNAME=391fa2c7e184
CONTAINER2
HOSTNAME=39123a43242asd4
CONTAINER3
HOSTNAME=123123123123
what i want:
CONTAINER1
HOSTNAME=APPNAME-391fa2c7e184
CONTAINER2
HOSTNAME=APPNAME-123fa2c7e184
CONTAINER3
HOSTNAME=APPNAME-343fa345e184
And want this to be autmatically set during startup of n-containers
how do i try to achieve this:
I try to set this in start.sh file called on container startup (pointed in ENTRYPOINT command in dockerfile):
#!/bin/sh
export HOSTNAME=something-$(hostname)
java $JAVA_OPTS -jar /app.jar
there is no effect, the HOSTNAME is not being changed
I don't think that the entrypoint script is right place to name your container, as it is already created at that point. You have a couple possibilities. Name it at runtime like this.
~
$ docker run -it -h myContainer 3bee3060bfc8 /bin/bash
[root#myContainer /]# echo $HOSTNAME
myContainer
[root#myContainer /]#
The -h option let's you name your container when you run it.
That value should be valid in your ENTRYPOINT script.
Or, if you want to create your container names more dynamically, you should name them in a docker compose file. Even if you don't use the container_name option, docker-compose will append -1
version: '2'
services:
myService:
container_name: myService-$(envVariable)
I don't know swarm, but as it works with a yaml file, you should get similar naming options.

pass parameters to docker entrypoint

I have Dockerfile
FROM java:8
ADD my_app.jar /srv/app/my_app.jar
WORKDIR /srv/app
ENTRYPOINT ["java", "-jar", "my_app.jar", "--spring.config.location=classpath:/srv/app/configs/application.properties"]
How I can do dynamic paramethers for java without ./run.sh in entrypoint? ( as -Dversion=$version or others )
I want pass this parameters when start container.
--entrypoint something doesn't work on Docker 1.11 ;(
You can append your dynamic parameters at the end of the docker run .... You haven't specified any CMD instruction, so it'll work.
What is actually run without specifying any command at the end, when running the docker run ..., is this:
ENTRYPOINT CMD (it's concatenated and there is a space in between)
So you can also use something like
...
ENTRYPOINT ["java", "-jar", "my_app.jar"]
CMD ["--spring.config.location=classpath:/srv/app/configs/application.properties"]
which means, when using
docker run mycontainer the
java -jar my_app.jar --spring.config.location=classpath:/srv/app/configs/application.properties
will be invoked (the default case), but when running
docker run mycontainer --spring.config.location=classpath:/srv/app/configs/some_other_application.properties -Dversion=$version
it'll be run w/ different property file and with the system property called version (overriding the default case)

Docker Compose JVM parameters

I wrote a java application that takes an environment variable that takes an argument to set a key for a JWT token salt key. Is there a way for me to pass the command variables in Docker Compose?
java -Djava.security.egd=file:/dev/./urandom -jar /user-profile-api.jar --key=blah
And to run the docker image you just
docker run -p 8080:8080 docker_image --key=blah
If you already are able to run your docker container using:
docker run -p 8080:8080 docker_image --key=blah
Then you just need to override the command attribute for your service in the compose file to --key=blah. So:
services:
app:
command: --key=blah
...
One way would be to put your java command in a shell script (say, bootstrap.sh), and set that as your command to run in docker compose. And then in bootstrap.sh inject the key via an environment variable which is in your docker-compose.yml.
E.g.
bootstrap.sh
java -Djava.security.egd=file:/dev/./urandom -jar /user-profile-api.jar --key=$SALT_KEY
docker-compose.yml
build: .
environment:
- SALT_KEY=blah
command: /opt/app/bootstrap.sh
Obviously you'd need to package up bootstrap.sh into your container for this to work.

Categories

Resources