How to run the latest docker container I created?

11.1k views Asked by At

When I'm debugging my Dockerfile, y constantly need to run these two commands:

$ docker build -t myuser/myapp:mytag - < myapp.docker # to create the container
$ docker run -i -t myuser/myapp:mytag /bin/bash       # to enter the container and see what's going on when something went wrong

("mytag" is usually something like "production", "testing", or "development". Not sure if I'm supposed to use tags this way)

But now the second command doesn't seem to work anymore: it's starting an old container. If I list all the containers with $ docker images, I see my tagged container in the 3rd place, and other untagged containers before it. If I use the ID of the 1st container it works fine, but it will be annoying to do it that way, I will have to search for its ID every time.

What am I doing wrong?

4

There are 4 answers

5
Ben Whaley On BEST ANSWER

It's important to be clear about containers vs images. It sounds like your tagged image is 3rd in the list of images, and that you believe the first image that only has n ID really should be tagged but it isn't. This probably means that there's a problem building the image. The docker build output is verbose by default and should show you the problem.

As an aside, I'm not entirely sure about your use case but the idea of having different containers for development, testing and production is an anti-pattern. The entire point is to minimize differences between execution environments. In most cases you should use the same image but provide different environment variables to configure the application as desired for each environment. But again, I'm sure there are reasons to do this and you may have a legitimate one.

1
Anaderi On

You just have to start and attach a container using:

docker start -i #ContainerID
1
manavortex On

Here's a few shortcuts that I've added to my .bashrc for easier development:

alias docker='sudo docker'
alias docker_clean_images='sudo docker rmi $(docker images -a --filter=dangling=true -q)'
alias docker_clean_ps='sudo docker rm $(docker ps --filter=status=exited --filter=status=created -q)'
alias dockerbuild='sudo docker build -m 4g -t "myname:latest" .'
alias dockerrun="sudo docker run -v path/to/dir/with/dockerfile/ -it myname /bin/bash"

By making sure I don't keep images around, I usually run the latest one, and since you can throw any parameters into the aliases, you can probably substitute one where you sort and filter docker container list by date (one of the other answers has that, I think)

1
Phlox Midas On

Here's what I use:

run_most_recent_container() { docker exec -it `docker ps -a --no-trunc -q | head -n 1` bash; }