Skip to content

Create, Run and Delete Container from Dockerfile

First, lets make a simple “hello world” that runs and outputs nodejs command from the container.

STEP 1

Create folder and put following files on the folder:

Dockerfile

# Specify a base image
FROM node:alpine
WORKDIR ‘/app’
# Install some dependencies
COPY ./package.json ./
RUN npm install
COPY ./ ./
# Default command
CMD [“npm”, “start”]
package.json
{
  “dependencies”: {
    “express”: “*”
  },
  “scripts”: {
    “start”: “node index.js”
  }
}
index.js
const express = require(‘express’);
const app = express();
app.get(‘/’, (req, res) => res.send(‘Hello World!’))
app.listen(8081, () => {
  console.log(‘Listening on port 8081’);
});
This will create a simple webserver that is listening port 8081 spitting out “Hello world!”
STEP 2
Build Docker Image and Run it
docker build .
This will create an image from the Dockerfile to your computer.
Tip: You can have multiple configurations, for example if you have different configuration for local development. Then use -f -flag to point to that like this: docker build -f Dockerfile.dev .
On the previous command docker created an image for you and passed you the image ID. It looks something like this on the console:
Successfully built 6bf0f35fae69
Now, you need to take this image ID and run like this:
docker run 6bf0f35fae69
Docker container is now running but we created the web server. The host has no idea how to access to this container so we need to do some port mapping.
Stop the container with CTRL+C
Then run the same command but with port mapping
docker run -it -p 8081:8081 6bf0f35fae69
On the port parameter ports are mapped as host:container
STEP 3
View and delete container
docker ps -a
docker rm CONTAINERID
To remove all containers
docker rm $(docker ps -a -q)
Check existing dockers on your system: docker images
Published inDockerUncategorized