# Dockerize and run nodejs app

> In this blog, we're going to see how to dockerize a simple http server in nodejs and run it inside a docker container.

### Create a nodejs app

* initialize a node package
    
    ```bash
    npm init -y
    ```
    
* create a new file *index.js* and copy & paste following code
    
    ```javascript
    const http = require("http");
    const dotenv = require("dotenv");
    dotenv.config();
    const PORT = process.env.PORT || 8080;
    http
      .createServer(function (req, res) {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.write(JSON.stringify({ message: "hello from server" }));
        res.end();
      })
      .listen(PORT, () => console.log(`Server is running on PORT: ${PORT}`));
    ```
    
* create a *.env* file to store secrets (port no. in our case)
    
    ```plaintext
    PORT=8888
    ```
    

### Create Dockerfile

* *Dockerfile* is used to tell docker to run instructions for building docker image
    
* let's add content to our *Dockerfile*
    
    ```dockerfile
    FROM node:20-alpine
    WORKDIR /app
    COPY package.json .
    RUN npm install
    COPY . .
    CMD ["node", "index.js"]
    ```
    

### Create .dockerignore

* *.dockerignore* file is used to exclude certain files & folders that are of no use or any secrets.
    
* In our case,
    
    * node\_modules
        
    * .env
        
    
    ```dockerfile
    node_modules
    .env
    ```
    

### Build docker image

* to build docker image with name **docker-node**
    
    ```bash
    docker build . -t docker-node
    ```
    
    * here, '-t' flag is used to specify docker image tagname (identifier)
        
* check if its built successfully
    
    ```bash
    docker images
    ```
    
    > this will show all available docker images including downloaded ones
    

### Run docker image

* as we haven't included our *.env* file, it needs to be included explicitly
    
    ```bash
    docker run -d -p 8888:8888 --env-file <env-file> docker-node
    ```
    
    > this will run docker image on port 8888
    > 
    > try to access it using url: http://localhost:8888
    
* **Let's break down what's happening**
    
    * *docker run* : this command runs docker image (downloads from docker hub if not available locally)
        
    * *\-d* : this flag is used to run container in detached mode, i.e., runs in background
        
    * *\-p* : it is used to expose ports of container to local machine. Here, first *8888* refers to local machine's port no & second *8888* refers to port no of container on which node app is running
        
    * *\--env-file* : to pass env variables to the container, *&lt;env-file&gt;* is filepath
        
    * *docker-node* : docker image name to run
        

> By using above steps, you can easily build and run docker image
