skip to content
shipanjodder.com

How to build docker images with Dockerfile

Updated:

A Dockerfile is a script containing a set of instructions to automate the building of Docker images. It defines everything required to set up a containerized environment.

Basic Structure of a Dockerfile

A Dockerfile typically includes:

CommandDescription
FROMSpecifies the base image (e.g., ubuntu, nginx, node)
LABELMetadata like maintainer information
RUNRuns commands during image build (e.g., install packages)
WORKDIRCopies files from the host to the container
COPYSpecifies the base image (e.g., ubuntu, nginx, node)
ADDLike COPY, but also supports URLs and tar extraction
ENVSets environment variables inside the container
EXPOSEDefines which ports the container will listen on
CMDDefault command executed when the container starts
ENTRYPOINTSimilar to CMD, but more flexible for argument handling

Example Dockerfile

# Step 1: Use an official base image
FROM ubuntu:latest
# Step 2: Set the maintainer label
LABEL maintainer="your-email@example.com"
# Step 3: Install required packages
RUN apt-get update && apt-get install -y curl vim
# Step 4: Set the working directory
WORKDIR /app
# Step 5: Copy files into the container
COPY myscript.sh /app/myscript.sh
# Step 6: Set environment variables
ENV MY_ENV_VAR=production
# Step 7: Expose a port
EXPOSE 8080
# Step 8: Default command to run the container
CMD ["bash", "myscript.sh"]

Building and Running a Dockerfile

After creating your Dockerfile, build an image and run it:

  • Build the Image
Terminal window
docker build -t my-image .

(-t assigns a tag to the image, . refers to the current directory)

  • Run a Container from the Image
Terminal window
docker run -d -p 8080:8080 --name my-container my-image