Filip
Filip

Reputation: 71

Get the name of running docker container inside shell script

I am currently developing an application, in which I want to automate a testing process to speed up my development time. I use a postgres db container, and I then want to check that the preparation of the database is correct.

My process is currently as follows:

docker run -p 5432:5432 --env-file=".db_env" -d postgres # Start the postgres db
# Prep the db, do some other stuff 
# ...
docker exec -it CONTAINER_NAME psql -U postgres

Currently, I have to to docker ps to get the container name and then paste it and replace CONTAINER_NAME. The container is the only one running, so I am thinking I could easily find the container id or the container name automatically instead of using docker ps to manually retrieve it, but I don't know how. How do I do this using bash?

Thank you!

Upvotes: 0

Views: 1409

Answers (4)

Filip
Filip

Reputation: 71

In the end, I took use of @mrcl's answer, from which I developed a complete answer. Thank you for that @mrcl!

CONTAINER_ID=$(docker run -p 5432:5432 --env-file=".db_env" -d postgres)
# Do some other stuff
# ...
docker exec -it $CONTAINER_ID psql -U postgres

Upvotes: 0

Marcel Neumann
Marcel Neumann

Reputation: 43

The container id is being returned from the docker run command:

CONTAINER_ID=$(docker run -p 5432:5432 --env-file=".db_env" -d postgres)

Upvotes: 3

Maroun
Maroun

Reputation: 95968

You can get its ID using:

docker ps -aqf "name=postgres"

If you're using Bash, you can do something like:

docker exec -it $(docker ps -aqf "name=postgres") psql -U postgres

Upvotes: 1

Michée Lengronne
Michée Lengronne

Reputation: 789

You can choose the name of your container with docker run --name CONTAINER_NAME.

https://docs.docker.com/engine/reference/run/#name---name

Upvotes: 1

Related Questions