Accessing A Docker Container from a CLI that doesn’t suck

Docker containers are great, but can sometimes be a little tricky to get into if you want to access the cli from terminal or command prompt. Docker Desktop has a CLI button that makes it super easy, but if you’ve ever tried using the terminal Docker opens, lets just say it has some room for improvement. So here we are trying to access the container from a CLI that doesn’t suck. since I’m on windows I’m using (cmd) command prompt with my first command being:

wsl

Because Windows Subsystem Linux makes windows SOO much better. If your on windows and haven’t setup wsl, do it (I think it’s required for docker on windows so definitely do it considering the subject of this tutorial).  next navigate to your docker directory using cd

cd somedir/where/your/you/have/your/docker_files

Now to access our container all we need to run is:

docker exec -it container_name /bin/sh

Note: When launching the CLI from docker desktop using the button, you can see this command is what they use to launch it at the top of the terminal widow that opens, only they use the container id instead of the container name.

Breakdown:

  • docker exec  the command to tell docker to run a command on a running container
  • -it this is 2 arguments: -i  aka –interactive and -t  for  –tty to allocate a pseudo-TTY.
  • container_name the name of the running docker container you wish to access.
  • /bin/sh the command executed on the container.  The documentation suggests bash here which can work if the container has bash on it, but /bin/sh consistently works so I use that.

Reference Source: Docker Documentation

But obviously you’ll need to replace the container name with the container you want to access. The container name might not be as obvious as it seems, but it’s not too hard to find. It is listed on docker desktop but since we are already in command line you can run:

docker ps

This outputs a chart of details for all the running containers you have up. The info may get a bit jumbled if your terminal window isn’t wide enough so instead of getting all the details we can instead get just the names like so:

docker ps --format {{.Names}}

 

Leave a Reply

Your email address will not be published. Required fields are marked *