A simple script to login to a docker container

docker whale

I have two versions: one for linux, and one for mac. If anyone knows how to combine them into one, please post in comments below!

The way it works is, rather than scrambling to find the container id where you want to login, you can provide to the script the partial name of the container as the only argument, and voila! If such a container exists, you will login to it. If more than one container matches the provided partial name, you will login to the first one.

You can find out which containers you're running, either locally in current folder or overall on the system, by running one of these commands:

docker ps

docker-compose ps

But to login to one of these containers you need the container id (not container name) and to spell out an exact command: docker exec -it $container_id /bin/bash

If you do this a lot you'll want to save time by not typing all of that every time. And you'd really want to go by container name, which you have memorized because you made is semantic - not the container id. So, you can use the scripts to do exactly that. 

So let's say you have containers `elastic_search_development`, `elastic_search_staging` and some others. You can login to the second one by running: 

./scripts/login search_staging 

Finally, here are the scripts. The first one is for linux, the second one is for mac.

#!/bin/bash
## file ./scripts/login
## for linux

if [ $# == "0" ]; then
  echo ""
  echo "$0 <app name>"
  echo ""
  exit 2
fi

set -ex

name=$1
container_id=`docker ps | grep $name | cut -d' ' -f 1 | head -n 1`

docker exec -it $container_id /bin/bash

set +ex
echo ok

.

#!/bin/bash
## file ./scripts/login_mac
## for mac

if [ $# == "0" ]; then
  echo ""
  echo "$0 <app name>"
  echo ""
  exit 2
fi

set -ex

name=$1
container_id=`docker ps | grep $name | cut -d' ' -f 1 | head -- -n 1`

docker exec -it $container_id /bin/bash

set +ex
echo ok

.

Please login or register to post a comment.