DEV Community

atrooo
atrooo

Posted on

Run and attach to a Docker container with a tiny command

For more information, see the Docker reference

This command runs an interactive (-i) container from the given image with an allocated tty (-t)

$ docker run -it image-name
Enter fullscreen mode Exit fullscreen mode

You can make a convenience function to execute this with a short command and the image name as an argument by adding the following to your .bashrc or .zshrc:

# run detached container, start interactive session
dat() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker run -it $image
}
Enter fullscreen mode Exit fullscreen mode

To use:

dat image:tho
Enter fullscreen mode Exit fullscreen mode

You'll need to reload your shell or run source ~/.zshrc (or ~/.bashrc) for the file changes to take effect.

Look you saved like 10 characters!

So what?

Ok so it's a little more reasonable when you start adding more options to the command...

For example, I found myself needing to build and run a container with an explicit platform set because I'm on an M1 chip and they're just fun like that.

# ~/.zshrc
datp() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi
  docker run -it --platform linux/x86_64 $image
}

dim() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker build -t $image -f Dockerfile .
}

dimp() {
  image=${1}
  if [ -z "$image" ]; then
    echo Please provide an image name
    return
  fi

  docker build -t $image -f Dockerfile --platform linux/x86_64 .
}
Enter fullscreen mode Exit fullscreen mode

Bam! With a dimp and a datp, I'm off to the races. The really slow races because I'm building for amd64 on an M1.

dimp myimage

datp myimage
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sso profile image
Sall

Nice, I am want to integrate something similar as testing kit to:

z.digitalclouds.dev/ 🧙‍‍♀️

However always struggling to find the time for it 🤦‍♂️ 😅