Docker project

Creating an image and sharing it on docker hub

We started the project by going to the official docker website: https://docs.docker.com/

In the Guide, Get Started, we choose:

  • Part 2: Containerize an application

https://github.com/docker/getting-started-app/tree/main

We can clone it using the command indicated in the repository on github or download the ZIP by clicking on <Code>.

Unzip the file.

Let’s view the code, edit it and start creating the image using Visual Studio Code or another source code editor.

Docker File

We need variables and settings  to create a Docker file.

Commands:

From : Which image will it load – Ubuntu, Alpine? And Platform – Node.js, Python?

Workdir : my application is in a folder, /app_docker_site . Instead of each command going to the app folder, the workdir will be: work in this directory, on what I specify.

Copy : copy and add all the files that are part of my application (from my local directory) to my image.

Run : where I’ll say: run this process/application. Start the application.

Env: environment settings, what I need inside my Linux, for example, to run this application

Expose : responsible for setting the port of my local host,

User: I can define a user to run this application

CMD : I can run some commands here or with
Entrypoint (to run commands)

On the Docker website it explains that the application is running on Node.js – JavaScript.
Within From he will have to have a version of Linux that runs Node.js (Ubuntu, Alpine, etc).
Alpine was chosen for this project.

Access the docker hub.

Put Node in the magnifying glass.

Check the version with tags

The further you scroll, the larger the image becomes. The oldest images are the heaviest.

For the application, we need at least an Alpine 18 version. This information can be found in the documentation for this image.

I log into my local machine, and opened my directory.
From this directory I will create my image with the name app.
To build it I will use:
docker build -i app .

Checking if my image has been created

* docker images
* Running the image: docker run -it app sh

Checking the node version

Explaining our Docker File and changing some code

You can come back to your code editor to proceed with the changes.

FROM  node:18-alpine    ( OS we are going to use)
WORKDIR /app
COPY . .    (we can copy a file here, e.g. json, yarn), here we will copy all the files in the /app directory, represented by the other dot. The directory is being made inside the /app defined in the WORKDIR.
RUN apk add –no-cache python3 g++ make   (installing python3 on Linux Alpine 18, in addition to nodejs it will have python) – check the version of your python first with the command: python -V
RUN yarn install –production    ( we use RUN when we are creating the image)
CMD [« node », « src/index.js »]    ( when I set up my container it has to run as soon as my container is created. It will run node and index.js. This command will make the application work. We use it when the image has already been created and we are going to run the application.)
EXPOSE 3000  (It is the number of the container’s gateway.)

Building the image again: docker build -t app

We will map the ports so the machine will recognize the application.
Let’s run mapping port 3000:3000
docker run -dp 3000:3000 app
-d to run in the background, p for it to map the port from 3000 to 3000 from the app image.

We type as url on the Web:  localhost:3000
Et voilá!

Our car app, or perhaps another list of objects, is working!

Docker Desktop

Clicking on the square with the blue arrow takes you to the web page where you can check out our image!

We can check our image on Docker Desktop

Congratulations! We have our application running on a Docker!

We can improve and optimize performance.


Docker stores the image information of each row (layer of each row) in the cache.
It runs from top to bottom.
To optimize, I have to separate the copy of my application with the dependencies of my application
In the case of our application, the changes to the dependencies are in the package.json.
If someone changed the json, we’d have to change the dependencies
Let’s move COPY . . down and insert COPY package.json . After WORKDIR /app
It will analyze: was there a change in package.json?
If not, it will follow and use the previous installation, run CMD or expose and the image will be built faster.

Let’s use this code in our Docker File.

It is only alter in the code editor:


FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN apk add –no-cache python3 g++ make
RUN yarn install –production
COPY . .
CMD [« node », « src/index.js »]
EXPOSE 3000

Create a new image with new settings

It took 38.4 seconds to create it.
When I make the same request, the system is optimized and the image is created in 0.9 seconds.
When we optimize an image the first time, it may not perform as well as we’d like, but the second time we run it, it performs very well.

You can create a new version of your image to keep an original one, one that will be shared or one with other settings.

I’ve created one with the version : V1.0.0

Going to the website: https://hub.docker.com

You can create a free account to download your image.

Create repository: Give your repository a name: Public , then: Create


Create a tag equal to the name of your repository on hub.docker.com.

Creating the tag

We need to write on your local machine: docker image tag (ID) repository name,

Ex:

docker image tag 9f0b41d78112 lilianb30/app: v1.0.0

You can check out the tag typing : docker images

Upload your image

  • docker login   (I wasn’t asked for a password because I already have Docker Desktop)

Docker Desktop will send all my information to the docker hub

docker push    (name of the repository in the hub and the version, if any, of your image)


docker push lilianb30/app:v1.0.0

Or you can click on the Docker Desktop
Images
Choose the image : Push to hub (beside)

You can check your image in the docker hub in your repository

Sharing an image to another machine without using the docker hub

We have to compress the image and then upload it. Save and load
I’ll name it appv1.tar (tar is a version of Linux where I can compress my files. It will come from the image app:v1.0.0)

I can then take this file and save it to a pendrive or a network drive and pass it on to another machine.

You can see the zipped file appv1.tar in my folder

Loading my app

docker image load -i appv1.tar 

Initializing a container

  • docker run -d app (app , name of my image)
  • docker ps (to view)

Renaming a container

  • docker run -d -name app_project1 app (-d run the container in the background)
    The new name will be app_project1 and the oldest one app

Checking Running status in Docker desktop

Difference between commands

  • docker run – to create a container
  • docker start and the name or ID to start an existing container
  • docker stop – to stop a container
  • docker rm ID or name, or docker rm -f name (for forced removal)

There are many possibilities for learning and practicing Docker.
On the website https://docs.docker.com there are more options and instructions with free manuals.
Playing around and executing the commands makes understanding this platform easier and will certainly make a big difference to your day-to-day work as a data engineer.

Vous allez aimer aussi:

Damos valor à sua privacidade

Nós e os nossos parceiros armazenamos ou acedemos a informações dos dispositivos, tais como cookies, e processamos dados pessoais, tais como identificadores exclusivos e informações padrão enviadas pelos dispositivos, para as finalidades descritas abaixo. Poderá clicar para consentir o processamento por nossa parte e pela parte dos nossos parceiros para tais finalidades. Em alternativa, poderá clicar para recusar o consentimento, ou aceder a informações mais pormenorizadas e alterar as suas preferências antes de dar consentimento. As suas preferências serão aplicadas apenas a este website.

Cookies estritamente necessários

Estes cookies são necessários para que o website funcione e não podem ser desligados nos nossos sistemas. Normalmente, eles só são configurados em resposta a ações levadas a cabo por si e que correspondem a uma solicitação de serviços, tais como definir as suas preferências de privacidade, iniciar sessão ou preencher formulários. Pode configurar o seu navegador para bloquear ou alertá-lo(a) sobre esses cookies, mas algumas partes do website não funcionarão. Estes cookies não armazenam qualquer informação pessoal identificável.

Cookies de desempenho

Estes cookies permitem-nos contar visitas e fontes de tráfego, para que possamos medir e melhorar o desempenho do nosso website. Eles ajudam-nos a saber quais são as páginas mais e menos populares e a ver como os visitantes se movimentam pelo website. Todas as informações recolhidas por estes cookies são agregadas e, por conseguinte, anónimas. Se não permitir estes cookies, não saberemos quando visitou o nosso site.

Cookies de funcionalidade

Estes cookies permitem que o site forneça uma funcionalidade e personalização melhoradas. Podem ser estabelecidos por nós ou por fornecedores externos cujos serviços adicionámos às nossas páginas. Se não permitir estes cookies algumas destas funcionalidades, ou mesmo todas, podem não atuar corretamente.

Cookies de publicidade

Estes cookies podem ser estabelecidos através do nosso site pelos nossos parceiros de publicidade. Podem ser usados por essas empresas para construir um perfil sobre os seus interesses e mostrar-lhe anúncios relevantes em outros websites. Eles não armazenam diretamente informações pessoais, mas são baseados na identificação exclusiva do seu navegador e dispositivo de internet. Se não permitir estes cookies, terá menos publicidade direcionada.

Visite as nossas páginas de Políticas de privacidade e Termos e condições.

Importante: Este site faz uso de cookies para melhorar a sua experiência de navegação e recomendar conteúdo de seu interesse. Ao utilizar nossos sites, você concorda com tal monitoramento.
Criado por WP RGPD Pro