Saturday, January 29, 2022

How to Execute Shell Script from Dockerfile

Recently I faced a problem with Docker build. Before we build the image there was a requirement to cleanup something from MongoDB. For that we tried to create shell script and execute it from Dockerfile before we start the service. Here in this blog I will explain how you can execute the shell script from Dockerfile. 

For that first create the shell script in the same context of Dockerfile. That means the file should be in the same folder or subfolder where Dockerfile is there. 

We can not access file outside the Docker build context so file has to be in the same folder.


You can put your content in this file for the tasks you want to do with this file. 

Now first we will copy the file in docker build context. So that it can be executed. This step is mandatory or else it will not find file. Add following lines of code in your Dockerfile.

FROM alpine3.15


Next step we have to change access rights of the script so it can be executed.

RUN chmod +x ./

Now since we have file in the Docker build context and it has proper access rights we can execute the file. 

RUN sh ./

That's it and now when to service starts it will execute the file and do all the actions which you have added in shell script.

Hope this helps you. 

No comments:

Post a Comment