At FlexStack we love the humble Dockerfile. They offer unparalleled flexibility (😉) and control, allowing you to specify exactly how your environment should be built, from the operating system up. This precision ensures that your applications run exactly as intended, in any environment, which is critical for reliable deployments.
Create your first Dockerfile
For the purposes of this exercise, we'll assume you've got a standard Node.js application. To get started, create a new file in the root of your application named Dockerfile
.
1. Start with a base image. First you need to define a base image. For web applications, node:lts-bookwork-slim
is a great start.
Breaking down what this line does:
-
FROM
initiates the build process from a base image, in this casenode:lts-slim
. This base image contains a Node.js runtime with long term support on top of a slim version of the Debian Bookworm release, optimized for size and minimal setup. Using a minimal image is important for significantly improving both the efficiency and security of your Docker image.
2. Set a working directory. This is where your application will live within the container.
3. Copy your code. Bring your application code into the Docker image.
COPY [source] [destination]
copies files from your system (source) at the.
path into the container filesystem (destination) in the/app
working directory we set in the previous step.
4. Install application dependencies.
RUN
executes commands during the container build process. Its effects are committed to the image and will persist when the container is started.
5. Expose application port. Make sure to expose the actual port your application runs on.
EXPOSE
is an instruction that indicates the container listens on specific network ports at runtime. You can expose more than one port e.g.EXPOSE 8080 80
.
6. Set the run command. Specify the command used to run your application.
CMD
is an instruction that tells Docker which command to run when the container is finally launched.