Docker Community Forums

Share and learn in the Docker community.

How run a script inside docker container?

I would like to run a script inside docker contaier.
Im using Ubuntu 18.04 and docker 19.03.8, there is a file I made with this content:

script.sh
docker exec -it postgres-12.2 psql -U postgres && \ l

It only run the first command. The “\ l” is to list the databases but actually I’m going to use other commands instead. The “\ l” is just to simplify the situation, the example.

This command would be executed when I needed it and not just when the container go up.

The “\ l” was just an example. I must replace it later with other n commands.

I tried this too but it didn’t work:

This will help me to make several tasks more automated when using Docker.

I need it to be calling a file (.sh).

script.sh is it outside docker?

Yes , its outside docker container.

Does anyone know how to solve?

You need to pass the commands to psql instead like this:

docker exec -it postgres-12.2 psql -U postgres -c "\l"

Thank you very much, it worked but I couldn’t run more than one command on postgres.

What’s wrong with that code? Because it does not work?

$ docker exec -it postgres-12.2 psql -U postgres -c “select ‘test’; && \l”

or

$ docker exec -it postgres-12.2 psql -U postgres -c “select ‘test’; \l”

Note: just simple examples.

$ docker exec -it postgres-12.2 psql -U postgres -c “command_1; command_2; command_n”

Ah yes my bad, -c only allows you to execute a single command. You can get around this by using -f myfile.psql and put your commands in the file. Does it work out for you?

Can’t find the file to run.
The terminal is in the same directory where the file is located, I tried it in some ways and it didn’t work:

docker exec -it postgres-12.2 psql -U postgres -f file.psql
docker exec -it postgres-12.2 psql -U postgres -f /file.psql
docker exec -it postgres-12.2 psql -U postgres -f ./file.psql

The file needs to be inside the container at the default location where docker exec puts you in. For the postgres:12.2 image, that’s simply root /. Find out with docker exec postgres-12.2 pwd

Docker I could publish my app image. How do i get it uploaded in docker hub it is saying publish failed

Follow these steps:
Use docker ps to get the name of the existing container.
Use the command docker exec -it /bin/bash to get a bash shell in the container.
Or directly use docker exec -it to execute whatever command you specify in the container.