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:
Command | Description |
---|---|
FROM | Specifies the base image (e.g., ubuntu, nginx, node) |
LABEL | Metadata like maintainer information |
RUN | Runs commands during image build (e.g., install packages) |
WORKDIR | Copies files from the host to the container |
COPY | Specifies the base image (e.g., ubuntu, nginx, node) |
ADD | Like COPY, but also supports URLs and tar extraction |
ENV | Sets environment variables inside the container |
EXPOSE | Defines which ports the container will listen on |
CMD | Default command executed when the container starts |
ENTRYPOINT | Similar to CMD, but more flexible for argument handling |
Example Dockerfile
# Step 1: Use an official base imageFROM ubuntu:latest
# Step 2: Set the maintainer labelLABEL maintainer="your-email@example.com"
# Step 3: Install required packagesRUN apt-get update && apt-get install -y curl vim
# Step 4: Set the working directoryWORKDIR /app
# Step 5: Copy files into the containerCOPY myscript.sh /app/myscript.sh
# Step 6: Set environment variablesENV MY_ENV_VAR=production
# Step 7: Expose a portEXPOSE 8080
# Step 8: Default command to run the containerCMD ["bash", "myscript.sh"]
Building and Running a Dockerfile
After creating your Dockerfile, build an image and run it:
- Build the Image
docker build -t my-image .
(-t
assigns a tag to the image, .
refers to the current directory)
- Run a Container from the Image
docker run -d -p 8080:8080 --name my-container my-image