Having a custom image would allow one to scale applications on-demand via orchestration (Kubernetes, Rancher, Kasm, etc) because they can be span up fin milliseconds straight from an image.
MAIN STEPS
- Create a new directory,
- Create a new file in that directory called
Dockerfile
, - Add the following blocks to the new file:
FROM
to use an specific basic image.RUN
to execute commands during the image build process.COPY
/ADD
to copy files or directories to the image.CMD
to specify the command that will be executed when a container is run from the image.
- Build the new image (with
docker build
and-t
to give it a name).
There are additional instructions that can be added as needed, such as:
ENV
to set environment variables in the image.EXPOSE
to declare what ports the container will listen at runtime.USER
is used to set the UID and/or GID that the command, run byCMD
, should be executed as.WORKDIR
defines the working directory for subsequent instructions, such asRUN
andCMD
.VOLUME
creates a persistent volume in the image (to survive container restarts).- and more.
Note: COPY
and ADD
are not the same. Essentially, COPY
only copies local files and directories from the build context to the image. While ADD
also supports automatically extract files from a compressed archive (such as a tar or zip file) and to copy files from a remote URL.
EXAMPLES
For the Dockerfile
:
FROM alpine:latest COPY ./hello.sh /usr/local/bin/hello RUN chmod +x /usr/local/bin/hello CMD ["/usr/local/bin/hello"]
FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt EXPOSE 80:5000/tcp CMD ["flask", "run", "--host=0.0.0.0"]
FROM postgres:12 ENV POSTGRES_DB dbHost ENV POSTGRES_USER dbUser ENV POSTGRES_PASSWORD dbPassword COPY init.sql /docker-entrypoint-initdb.d/ EXPOSE 5432
For the build:
sudo docker build -t customImageName .
EXTRACT IMAGE CONTENT
Sometimes it is needed to extract the content of a Docker Image for analysis.
sudo docker save USER/IMAGE > USER_IMAGE.tar tar xvf USER_IMAGE.tar
Or from a Docker Container:
sudo docker export CONTAINER > CONTAINER.tar tar xvf USER_IMAGE.tar