Save Docker image as a tar file

mihalis's picture

In this blog post I am going to tell you how to save a Docker image as a tar file and how to use that tar file afterwards.

First, you will need to have a Dockerfile:

$ cat Dockerfile
FROM golang:alpine
RUN mkdir /files
COPY hw.go /files
WORKDIR /files
RUN go build -o /files/hw hw.go
ENTRYPOINT ["/files/hw"]

Then, you will need to create a Docker image from that Dockerfile:

$ docker build -t go_hw:v1 .
Sending build context to Docker daemon 134.1kB
Step 1/6 : FROM golang:alpine
alpine: Pulling from library/golang
cd784148e348: Pull complete
7e273b0dfc44: Pull complete
952c3806fd1a: Pull complete
ee1f873f86f9: Pull complete
7172cd197d12: Pull complete
Digest: sha256:198cb8c94b9ee6941ce6d58f29aadb855f64600918ce602cdeacb018ad77d647
Status: Downloaded newer image for golang:alpine
---> f56365ec0638
Step 2/6 : RUN mkdir /files
---> Running in 6281fe42eb5b
Removing intermediate container 6281fe42eb5b
---> 8dd252caee51
Step 3/6 : COPY hw.go /files
---> a06ad8bf8b54
Step 4/6 : WORKDIR /files
---> Running in aaea454a1320
Removing intermediate container aaea454a1320
---> 512077e5d14d
Step 5/6 : RUN go build -o /files/hw hw.go
---> Running in e5474648eefe
Removing intermediate container e5474648eefe
---> 61e930e48a5a
Step 6/6 : ENTRYPOINT ["/files/hw"]
---> Running in f5ca2e84ada1
Removing intermediate container f5ca2e84ada1
---> 492dda632ae1
Successfully built 492dda632ae1
Successfully tagged go_hw:v1

After that you are ready to save that Docker image:

$ docker save go_hw:v1 -o go_hw.tar
$ ls -l go_hw.tar
-rw------- 1 mtsouk staff 319876096 Jan 6 20:26 go_hw.tar

After that you can distribute your Docker image any way you want and load it as follows:

$ docker load -i go_hw.tar
7bff100f35cb: Loading layer 4.672MB/4.672MB
b14874cfef59: Loading layer 838.7kB/838.7kB
789935042c6f: Loading layer 2.56kB/2.56kB
61b145086eb8: Loading layer 312.4MB/312.4MB
e121936484eb: Loading layer 2.56kB/2.56kB
c53a945a0db2: Loading layer 1.536kB/1.536kB
323c5d051144: Loading layer 2.56kB/2.56kB
ed9b85466379: Loading layer 1.93MB/1.93MB
Loaded image: go_hw:v1

The output of docker images will verify that the docker image is ready for use:

$ docker images
go_hw v1 492dda632ae1 3 minutes ago 312MB