My Springboot Application is running fine in IDE but when I create fat jar file and run on docker it gives the error. I am connecting my application with firebase so i want to include the serviceAccountKey.json file from the resource folder. The application runs fine in my ide, but while deploying it over the docker container it gives the error of file not found. Though when include the file and print it path it doesn’t give any sort of error . But when i give the file path to fileInputStream it produces the error. I have tried multiple ways but nothing seems to work. I’m including the file using classLoader.getResource(“filename.json”).
I tried to skip the inclusion of file and do it by saving files content in a string and then sending it to stream but this method crashes the server whenever i query firebase.
this is the code where error is occurring. Notice that I’m printing the file path and it gets printed in the output before showing error. I have also tried file.getAbsoluteFile instead of path but doesn’t work. Probably I’m doing it wrong or probably i have to mention the path in some other place as well which i don’t know about. If anyone has done this before then please help me on this.
File path is getting printed but FileStream can’t get it
Advertisement
Answer
An alternative to having a credential in a json file that is packaged with the application, would be that you set an environment variable upon starting the application, and instead load the key via application.yml. This way, you don’t need to package the secrets into the application jar file.
1. create config class
@Configuration @ConfigurationProperties(value = "my-custom-config") public class MyConfig { private String serviceAccountKey; // getters/setters etc. if not using lombok }
2. use above config
in other spring beans by injecting the config class, and retrieve the secret with getter, e.g. config.getServiceAccountKey();
3. Add config to your application.yml file
# application.yml my-custom-config: serviceAccountKey: ${ENV_VARIABLE_NAME} # <---- this way you can bind an env variable to your config.
4. Define env variable in container on startup
On instantiating the docker container, provide env option and define an environment variable.
docker run -env ENV_VARIABLE_NAME=<value> ...