DEV Community

Tirtha Guha
Tirtha Guha

Posted on • Edited on

Reusing Images: Publishing to a registry

Ok, so here's we're going to learn how to reuse images. We often follow the principle of build once deploy anywhere and for that we need to maintain our images in a repository for later reuse.

For this tutorial, we'll use amazon ECR. I've logged into Amazon AWS console and searched for ECR.

Create a repository

The best way to create a repository is probably to follow this https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html. It even describes how to create an IAM user and use that to manage the ECR interactions, instead of using the root account.

The repository I've created is called blogrepo

Creating and Pushing an image.

For this, we're going to create a bare minimum express application and a Dockerfile

user@host:~/ecr-push-demo-app$ touch Dockerfile
user@host:~/ecr-push-demo-app$ touch app.js
user@host:~/ecr-push-demo-app$ touch package.json
user@host:~/ecr-push-demo-app$ npm install express --save
Enter fullscreen mode Exit fullscreen mode

Put the following in these files

In app.js

//app.js
var express = require("express");
var app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get("/", function (req, res, next) {
  res.send({ title: "Express", application: "Application 1" });
});

app.listen(3000, () => console.log("Running on http://localhost:3000"));
Enter fullscreen mode Exit fullscreen mode

In package.json

{
  "name": "ecr-push-demo-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

and finally, in the Dockerfile

FROM node:12-slim
WORKDIR /app
COPY ./package*.json ./
RUN npm install
COPY ./ ./
EXPOSE 3000

# Run the code
CMD [ "npm", "start" ]
Enter fullscreen mode Exit fullscreen mode

Build the image

Lets build the image and tag it as blogrepo20201120

$ sudo docker build -t blogrepo20201120 .
Enter fullscreen mode Exit fullscreen mode

Lets tag this image for pushing to ecr and then push the image

Just a reminder, the repository I've created on ECR console is called blogrepo and I created this in ap-south-1 region

$ docker tag blogrepo20201120:latest your_aws_account_id.dkr.ecr.ap-south-1.amazonaws.com/blogrepo:latest
$ docker push your_aws_account_id.dkr.ecr.ap-south-1.amazonaws.com/blogrepo:latest
Enter fullscreen mode Exit fullscreen mode

Lets see if we can pull the image and run it

$ docker pull your_aws_account_id.dkr.ecr.ap-south-1.amazonaws.com/blogrepo:latest
$ sudo docker run -p 3000:3000 -d your_aws_account_id.dkr.ecr.ap-south-1.amazonaws.com/blogrepo:latest
Enter fullscreen mode Exit fullscreen mode

That's all. Just open your browser to http://localhost:3000

Top comments (0)