Inserting certificates into Java keystore via Dockerfile


Scenario

You have a Root CA and Issuing CA certificate that you need to import into the Java keystore of a Docker image to allow your application to make trusted calls to another secured site signed by your Issuing CA.


Create the below Dockfile to install Java, copy your certificates from your host system (relative path is ./certs) to the Docker image and use the keytool command to import the certificates into the the default Java keystore ($JAVA_HOME/lib/security/cacerts).

You will obviously want to customize this to suit your needs adding your Java application server (i.e. Apache Tomcat, Wildfly, etc.) and copy your code into the Docker image via the Dockerfile as well.

Dockerfile

FROM registry.access.redhat.com/rhel7.1

ENV JAVA_HOME=/usr/lib/jvm/jre

COPY ./certs/My_Root_CA.cer /etc/ssl/certs/
COPY ./certs/My_Issuing_CA.cer /etc/ssl/certs/


RUN yum clean all && \
    yum --releasever=7.1 swap -y -- remove systemd-container\* -- install systemd systemd-libs && \
    yum update -y --releasever=7.1 && \
    yum install java-1.8.0-openjdk --releasever=7.1 -y && \
    yum clean all && \
    $JAVA_HOME/bin/keytool -storepasswd -new mysecretpassword -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit && \
    echo "yes" | $JAVA_HOME/bin/keytool -import -trustcacerts -file /etc/ssl/certs/My_Root_CA.cer -alias my-root-ca -keystore $JAVA_HOME/lib/security/cacerts -storepass mysecretpassword && \
    echo "yes" | $JAVA_HOME/bin/keytool -import -trustcacerts -file /etc/ssl/certs/My_Issuing_CA.cer -alias my-issuing-ca -keystore $JAVA_HOME/lib/security/cacerts -storepass mysecretpassword && \
    rm -f /etc/ssl/certs/My_Root_CA.cer &&\
    rm -f /etc/ssl/certs/My_Issuing_CA.cer

Command

Next you will need to build your docker image using the docker build command.

docker build -t myprivatedockerregistry:5000/rhel7.1-with-my-certs .

Your containerized application will now trust certificates signed by your Issuing CA.