Build and run Dockerfile with one command
Is it possible to build image from Dockerfile and run it with a single command?
There is one command docker build
to build a Dockerfile and docker run -it
to run the image.
Is there any combination of these two commands to make it easier to build and run with just one command?
If you want to avoid tagging, docker build -q
outputs nothing but the final image hash, which you can use as the argument to docker run
:
docker run -it $(docker build -q .)
And add --rm
to docker run
if you want the container removed automatically when it exits.
docker run --rm -it $(docker build -q .)
No, there is no single command. But if you tag your image as you build it, it will be easier to run:
docker build -t foo . && docker run -it foo
I use docker-compose for this convenience since most of the apps I'm building are talking to external services sooner or later, so if I'm going to use it anyway, why not use it from the start. Just have docker-compose.yml as:
version: "3"
services:
app:
build: .
and then just run the app with:
docker-compose up --build app
It will rebuild the image or reuse the container depending on whether there were changes made to the image definition.
Recently I started getting a promo message about using docker scan
after every build.
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
Here's what I used to do:
docker build -q .
and here's what is working now:
docker build -q . | head -n1
If you use Makefile, I find this snippet useful:
build:
@docker build . | tee .buildlog
bash: build
@docker run --rm -it $(shell grep "Successfully built" .buildlog | cut -d ' ' -f 3) /bin/bash
You don't need tagging, like in @jonathon-reinhart answer, but you also get the build output.