DEV Community

Cover image for Docker for Beginners: Containerizing Your First Application
danielfilemon
danielfilemon

Posted on

Docker for Beginners: Containerizing Your First Application

If you've heard about Docker but never used it, this guide is for you. Docker is a platform that allows you to create, distribute, and run applications in isolated containers. This means you can run your application in any environment without worrying about OS differences or dependencies.

First, you need to install Docker. Visit the official website (https://www.docker.com/get-started), download, and install Docker Desktop for your operating system. After installation, check if everything is working by running the following command in your terminal:

If everything is set up correctly, Docker will return the installed version.

Creating Your First Application
Let's create a simple web server using Node.js and Docker. First, create a project folder and a server.js file:

mkdir my-docker-project && cd my-docker-project
Now, create the server.js file and add the following code:

const http = require("http");

const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Docker!\n");
});

const PORT = 3000;
server.listen(PORT, () => {
console.log(Server running at http://localhost:${PORT});
});
Next, create a Dockerfile in the same folder with the following content:

Use the official Node.js image

FROM node:18

Set the working directory inside the container

WORKDIR /app

Copy project files into the container

COPY . .

Expose port 3000

EXPOSE 3000

Command to run the server

CMD ["node", "server.js"]
Now, to build the Docker image, run the following command in your terminal:

docker build -t my-server .
This command creates an image called my-server. Now, let's run it inside a container:

docker run -p 3000:3000 my-server
This starts the container and maps port 3000 from the container to port 3000 on your computer. Now, open your browser and go to http://localhost:3000, and you will see the message "Hello, Docker!".

Top comments (0)