简体   繁体   中英

How to execute commands inside docker container from Jenkins

My requirement is to manually add certificate to the keystroe in Java which is in container. For this , I am using below commands.

sudo docker exec -it my-container-name bash --> to go inside container

cd /java/lib/security -- > chnage directory to java security path

keytool -keystore cacerts -storepass changeit -noprompt -trustcacerts -importcert -alias testcert -file /cert/test-Base64.cer --> install certificate

The above commands are working fine. Now, I would like to automate this from Jenkins. I mean, i want these commands to be executed after ' sudo docker-compose up -d ' .

Can anyone please help.

如果您在容器启动后仍想这样做,请使用

sudo docker exec -it my-container-name bash -c "cd /java/lib/security; keytool -keystore cacerts -storepass changeit -noprompt -trustcacerts -importcert -alias testcert -file /cert/test-Base64.cer"

You should generally find ways to avoid docker exec , especially for scripted use like this. (It's very conceivable that automated tasks will delete and recreate containers and won't have your manual setup steps. This is doubly true in clustered environments like Docker Swarm or Kubernetes.)

In the case where you have some existing keystore file that you just want to inject into the container, the easiest way is to push it in at startup time using the docker run -v option. You'd need a fully populated keystore file already.

docker run \
  -v $PWD/keystore.jks:/usr/lib/java/jre/lib/security/keystore.jks \
  ...

If you can't inject a fully populated keystore file at startup time, you can write a script that runs at container startup time. It looks for some well-known directory, runs the keytool command on every file there, and then runs the command it was passed as command-line arguments.

#!/bin/sh
if [ -d /cert ]; then
  for f in /cert/*.cer; do
    keytool ... -file "$f"
  done
fi
exec "$@"

In your Dockerfile, COPY this script in and make it the ENTRYPOINT. If you previously had an ENTRYPOINT ["java", ...] line, change that to a CMD. This will look something like

FROM java:8
...
COPY entrypoint.sh /app
ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["java", "-jar", "/app/myapp.jar"]

Then when you run the container, inject the /cert directory

docker run \
  -v $PWD/cert:/cert \
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM