Quickly open a Bash in your Docker Container

I find myself using Docker more and more, whether for quickly trying out things but also for developing larger projects1. Especially when I am just about to try something quickly I most often find myself creating a Bash in the Docker container, to poke around or look at logs. I grew a bit tired always typing the same stuff over and over and looked for a way to do so easier.

So I am still a bit caught in between having a docker-compose setup and “bare” Docker containers. So it was always a bit of forth and back between docker exec -ti and docker-compose exec. With a bit of fiddling I was able to come up with a small shell script to try both variants.

The script

dssh() { 
    COMPOSE_CONTAINER=$(docker-compose ps -q "${DOCKER_CONTAINER}" 2&>1)
    if [[ $? == 0 ]]; then

    docker exec -ti "${DOCKER_CONTAINER}" /bin/bash 


dssh laravel

I added this to my ~/.zshrc, so I can use it at any time. While I only tested it in a ZSH environemtn, it should also work in most other shells, e.g. Bash (.bashrc).


docker-compose will create container names based on the schema <folder>_<name>_<count>. So for example, I have a docker-compose.yml in my project folder mailsystem defining a container named laravel. Internally docker-compose will resolve this to mailsystem_laravel_1. Now it would have to always type out docker exec -ti mailsystem_laravel_1 /bin/bash. Way too lazy for this. That’s why there is also docker-compose exec laravel /bin/bash which will do the same.

A cirectly created Docker container will have that exact name I gave it, so it would be docker exec -ti laravel /bin/bash. To combine both, we can take advantage of docker-compose ps -q <container>. This returns the ID of a docker container, which can be fed to docker exec as well. Of course, if none of these attempts succeed, to command will ultimately fail.

I hope it saves you some typing as well.

  1. I still have to jump ship for running Docker in production.