kdeng / my-blogs

Kefeng's blogs
0 stars 0 forks source link

Create a bash docker image from scratch #6

Open kdeng opened 6 years ago

kdeng commented 6 years ago

Since I spent more time on Python and Golang, I would like to try to build a docker image from scratch to support a web application in Go or Python, even JVM. So, the first step is to build a docker image to support bash or sh command.

The scratch docker image doesn't contain anything at all. It is a totally empty docker image, so I need to copy the things one by one.

Now, create a new folder to start the thing from scratch.

# on my local
mkdir -p ~/works/docker-bash/data
touch ~/works/docker-bash/Dockerfile
cd ~/works/docker-bash

In order to get runnable bash/sh/echo binary file, I will launch a Debian container to download those files.

cd ~/works/docker-bash/data
docker run -it --rm -v `pwd`:/data debian:latest sh -c "bash"

My intent is to run some applications by using a dynamic linked library, thus I have to download those dependent libraries.

# in the container

# Prepare the folder structure in new docker image
mkdir -p /data/lib64
mkdir -p /data/lib/x86_64-linux-gnu
mkdir -p /data/bin

# Copy all dependent libraries
cp /lib/x86_64-linux-gnu/ld-2.24.so /data/lib/x86_64-linux-gnu/.
cp /lib/x86_64-linux-gnu/libtinfo.so.5 /data/lib/x86_64-linux-gnu/.
cp /lib/x86_64-linux-gnu/libdl.so.2 /data/lib/x86_64-linux-gnu/.
cp /lib/x86_64-linux-gnu/libc.so.6 /data/lib/x86_64-linux-gnu/.
cd /data/lib64 && ln -sv ../lib/x86_64-linux-gnu/ld-2.24.so ./ld-linux-x86-64.so.2

# Copy binary files.
cp /bin/bash /data/bin/.
cp /bin/sh /data/bin/.
cp /bin/echo /data/bin/.

As far as now, I have downloaded all dependencies from Debian container.

So, copy following content into Dockerfile:

FROM scratch
COPY ./data/. /
ENTRYPOINT [ "/lib64/ld-linux-x86-64.so.2" ]
CMD [ "/bin/bash" ]

And build a new docker image with docker build . -t docker-bash.

So, I can start a container by docker run -ti --rm docker-bash now.

Some reference links are below.

  1. https://forums.docker.com/t/simple-hello-c-compiled-runs-on-mac-but-not-in-container/26553/2
  2. https://letitknow.wordpress.com/2014/09/14/minimalistic-docker-starting-from-scratch/
  3. http://blog.xebia.com/create-the-smallest-possible-docker-container/
  4. http://glaudiston.blogspot.com/2015/06/how-to-make-very-very-small-docker.html
  5. https://medium.com/@pierreprinetti/the-go-dockerfile-d5d43af9ee3c