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 projects[^fn1]. 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

~/.zshrc
dssh() {
DOCKER_CONTAINER=$1
COMPOSE_CONTAINER=$(docker-compose ps -q "${DOCKER_CONTAINER}" 2&>1)
if [[ $? == 0 ]]; then </div></div>
</span>DOCKER_CONTAINER="${COMPOSE_CONTAINER}"
fi </div></div>
</span>docker exec -ti "${DOCKER_CONTAINER}" /bin/bash
}
</pre></div></figure> ## Usage
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`). ## Background `docker-compose` will create container names based on the schema `__`. 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 `. 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. [^fn1]: I still have to jump ship for running Docker in production.