<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lal Zada on Medium]]></title>
        <description><![CDATA[Stories by Lal Zada on Medium]]></description>
        <link>https://medium.com/@BuildWithLal?source=rss-e838a8160361------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o5onMjdyVynC-C93ONw0CQ.png</url>
            <title>Stories by Lal Zada on Medium</title>
            <link>https://medium.com/@BuildWithLal?source=rss-e838a8160361------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:39:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@BuildWithLal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automate FastAPI Deployment to AWS ECS with GitLab CI]]></title>
            <link>https://aws.plainenglish.io/automate-fastapi-deployment-to-aws-ecs-with-gitlab-ci-311753e51a90?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/311753e51a90</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 07:02:17 GMT</pubDate>
            <atom:updated>2024-12-04T06:43:28.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K7p-2rRSh2u6Hy7K-XCtQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@homaappliances?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Homa Appliances</a> on <a href="https://unsplash.com/photos/a-large-machine-in-a-large-building-pWUyHVJgLhg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Imagine pushing a single button and watching your code deploy itself to a server. No <em>manual steps </em>— just smooth, automated deployment from GitLab to AWS. If you’re managing multiple deployments or frequently updating your app, automated deployment is the recommended way.</p><p>In this article, we’ll cover exactly how to set up an automated CI/CD pipeline for a <a href="https://medium.com/python-in-plain-english/dockerize-fastapi-for-development-and-production-4a2adfd722f2">Dockerized FastAPI app</a>, all the way from setting up an AWS ECS Cluster and Service, IAM Roles and GitLab CI/CD.</p><p>In our <a href="https://medium.com/python-in-plain-english/dockerize-fastapi-for-development-and-production-4a2adfd722f2">previous article</a>, we have already covered how to dockerize FastAPI app for both local development and production so we’ll continue it from that production-ready Dockerfile.</p><p><a href="https://python.plainenglish.io/dockerize-fastapi-for-development-and-production-4a2adfd722f2">Dockerize FastAPI for Development and Production</a></p><p>To keep things organized, we’ll set up our files as follows:</p><pre><br>fastapi-app<br><br>          ├── app # FastAPI app code<br><br>          ├── docker<br>                   ├── Dockerfile # development<br>                   ├── Dockerfile.prod<br>                   ├── entrypont.sh # development<br>                   ├── entrypoint.prod.sh          <br><br>          ├── aws<br>                   ├── update-ecs-task.py<br><br>          ├── docker-compose.yml # For local dev<br>          ├── requirements.txt<br>          ├── gunicorn.conf.py<br>          ├── .gitlab-ci.yml<br>          </pre><p>What we are going to cover:</p><ol><li>Set Up ECS Cluster, Service and Task Definition</li><li>Create IAM Roles for GitLab CI</li><li>Create GitLab CI</li><li>Create Deployment Script</li></ol><h3>Set Up ECS Cluster</h3><p>We’ll deploy our app on<a href="https://aws.amazon.com/ecs/"> AWS ECS (Elastic Container Service)</a> which is a managed solution for running Dockerized applications, offering flexibility to choose between Fargate (serverless) and EC2 for your workloads.</p><p>Choose Fargate for no infrastructure management, or EC2 for more control and customization over the infrastructure.</p><p>Please follow the steps below to have an ECS cluster up and ready to serve a dockerized FastAPI app.</p><ul><li>Go to <a href="https://us-east-1.console.aws.amazon.com/ecs/v2/clusters">AWS ECS</a> → Click on <strong>Create Cluster</strong></li><li>Give your cluster a name fastapi-app</li><li>Select AWS Fargate (serverless) under the <strong>Infrastructure</strong></li><li>Keep rest of the things as default and click on Create</li></ul><blockquote>Hold ON for a while so your cluster could up and run by AWS.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJBbH0blAZsu7nuBlaWR1g.png" /></figure><h3>Create Task Definition</h3><p>A task definition is like a blueprint that tells ECS how to run your application, including which containers to use and their settings.</p><ul><li>Go to <a href="https://us-east-1.console.aws.amazon.com/ecs/v2/task-definitions">AWS Task Definition</a> → Click on <strong>Create New Task Definition</strong></li><li>Give your Task Definition a name fastapi-app</li><li>Select AWS Fargate (serverless) under the <strong>Infrastructure</strong></li><li>Under the Task Size, set CPU to 0.5 and Memory to 1 GB</li><li>Under the Task execution role, select Create new role so AWS will auto create the required IAM role.</li><li>Under the Container details, Give the container a name fastapi-app and set the Image URI<strong> </strong>to your Container Registry. We’ll use GitLab registry so i’ll set it to registry.gitlab.com/build-with-lal/fastapi-app:latest and will enable private authentication later once we get a GitLab Access token. We’ll also replace the docker image tag :latest dynamically inside our GitLab pipeline later.</li><li>Under the Port mappings, Set Container port to 80</li><li>Under the Environment Variables, add a Key with APP_PORT and Value 80 so FastAPI app inside the container will run on port 80.</li><li>Keep rest of the things as default and click on Create</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWBONk5f9ndZ12l6zXz0OA.png" /></figure><h3>Create Service and Task</h3><p>A task is a single instance of your application running on ECS, while a service ensures that the correct number of tasks are always running and available. A service spins up tasks based on the provided task definition, and each task launches a container using the specified Docker image tag.</p><ul><li>Go to <a href="https://us-east-1.console.aws.amazon.com/ecs/v2/home?region=us-east-1">AWS ECS</a> → Select your cluster i.e fastapi-app</li><li>Under the Services, Click on Create</li><li>Under the Compute configuration, select Launch type and make Fargate is selected under the Launch type</li><li>Under the<strong> </strong>Application type, make sure Service is selected</li><li>Under the Family, Select your task definition i.e fastapi-app and make sure Latest is selected under the revision.</li><li>Give service a name i.e fastapi-app</li><li>Service type → Replica and Desired tasks set to 1</li><li>Turn OFF Availability Zone</li><li>Under the Deployment options, set Deployment type to Rolling Update and Min running tasks and Max running tasks set to 100% and 200% respectively.</li><li>Under the Networking, Choose your desired VPC and Subnets</li><li>Under the Security Group, Create New Security Group and add an Inbout Rule with Type HTTP,port set to 80 and Source set to anywhere . Make sure Public IP is Turned ON</li><li>Keep rest of the things as default and click on Create</li></ul><blockquote>Wait a minute so the AWS could create ECS service and then Service create a task and spin up the desired container.</blockquote><p>Once the service is created. Go to your cluster and Go to the Tasks tab.</p><p>Under the Tasks tab, you should be seeing a task is trying to provision. But eventually they will fail with this message.</p><pre>CannotPullContainerError: pull image manifest has been retried 1 time(s):<br>failed to resolve ref registry.gitlab.com/build-with-lal/fastapi-app:latest:<br>failed to authorize: failed to fetch anonymous token: unexpected status from <br>GET request to https://gitlab.com/jwt/auth?scope=repository%3Abuil:<br>403 Forbidden</pre><p>Lets fix this by adding GitLab access to the Task Definition.</p><h3>GitLab Registry Access in Task Definition</h3><p>Since our GitLab registry is private and it requires authentication, we need to:</p><ul><li>Get an Access Token from GitLab</li><li>Add it to AWS Secret Manager</li><li>Use that Secret inside our Task Definition</li></ul><p>Get GitLab Access Token <a href="https://gitlab.com/-/user_settings/personal_access_tokens">here</a> by creating a new Personal Access Token with read_registry and write_registry permissions.</p><p>Copy access token from GitLab once created.</p><p>Now Go to <a href="https://us-east-1.console.aws.amazon.com/secretsmanager/home">AWS Secret Manager</a></p><p>Click on Store a New Secret → Select Other type of secret → Add your GitLab username and access token as shown below. Please note that the access token key name is password but the value should be the access token we just created in our GitLab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Dh0zqM7door4ijqVHx-RA.png" /></figure><p>Click on Next → Give secret a Name i.e fastapi-app → Leave other options as default and click Store</p><p>Once created, Go to your secret and copy its secret ARN which should look like this arn:aws:secretsmanager:us-east-1:AWS_ACCOUNT_ID:secret:gitlab-fastapi-app-access-token-****</p><p>Now Go Back to ECS Task Definitions → Select your Task Definition i.e fastapi-app → Click on Create new revision → Scroll down to Container details → Enable Private Registry Authentication → Paste Secret ARN → Scroll down and Click on Create.</p><h3>Update ECS Task Execution Role</h3><p>For the ECS Task to work with AWS Secret manager and fetch GitLab Access token from Secret Manager, we need to update <strong>ecsTaskExecutionRole</strong> in IAM.</p><p>Go to <a href="https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#"><strong>IAM</strong></a><strong> → Roles → ecsTaskExecutionRole → Add Permissions → Attach Policies → </strong>Select<strong> SecretsManagerReadWrite → Add Permissions</strong></p><h3>Test GitLab Registry Authentication</h3><p>Go to your ECS cluster → Select your service → Click on Update → Select Force New Deployment → Under the Task Definition, Select Latest Revision → Scroll Down and Click on Update</p><p>Now check back your Tasks tab under your Cluster and unauthorized error should be gone. now we should have unavailable tag error because we don’t have any docker image yet in our GitLab Registry so this will be fixed once we push our docker image through GitLab CI.</p><h3>AWS IAM Roles for GitLab CI</h3><h4>1. IAM Identify Provider</h4><p>The first thing we need to do in terms of giving access to AWS from GitLab, is to setup an IAM <strong>identity provider</strong>.</p><p>Identity provider (Idp) is used to manage your user identities outside of AWS, but grant the user permissions to use AWS resources in your account. This is exactly what we need to do, stay in the GitLab but give access to our EC2 instance in AWS without exposing any secret keys to GitLab.</p><p>Go <strong>AWS IAM → Identity providers → Add Provider</strong></p><p>On the next screen, select <strong>OpenID Connect</strong></p><p>Set both <strong>Provider URL</strong> and <strong>Audience</strong> to <a href="https://gitlab.com/">https://gitlab.com</a></p><p>Click on Add Provider</p><h4>2. IAM Role For Identity Provider</h4><p>Go to <strong>AWS IAM → Roles → Create Role</strong></p><p>On the next screen, select <strong>Web Identity</strong></p><p>Under the Web identity<strong>, </strong>Select GitLab as Identity Provider and Audience</p><p>Click on Add condition → set Key to gitlab.com:sub → set Condition to StringEquals → set Value to project_path:build-with-lal/fastapi-app:ref_type:branch:ref:master</p><blockquote>Make sure to update your project path username/project_name i.e build-with-lal/fastapi-app and branch name i.e master</blockquote><p>On the next screen for permissions, Attach <strong>AmazonECS_FullAccess</strong></p><p>Give the role a name i.e GitLab<strong> → </strong>Add role</p><h3>Create the GitLab CI/CD Pipeline</h3><p>1. <strong>Add </strong><strong>.gitlab-ci.yml</strong></p><p>Add .gitlab-ci.yml to your GitLab project root directory.</p><p>.gitlab-ci.yml</p><pre>build:<br>  stage: build<br>  image: docker<br>  services:<br>    - docker:27.2.0-dind<br>  variables:<br>    DOCKER_HOST: tcp://docker:2376<br>    DOCKER_TLS_CERTDIR: &quot;/certs&quot;<br>  script:<br>    - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin<br>    - docker build -t &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot; -f ./docker/Dockerfile.prod .<br>    - docker push &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;<br><br>deploy:<br>  stage: deploy<br>  image:<br>      name: amazon/aws-cli<br>      entrypoint: [&quot;&quot;]<br>  id_tokens:<br>    GITLAB_OIDC_TOKEN:<br>      aud: https://gitlab.com<br>  variables:<br>    AWS_DEFAULT_REGION: us-east-1<br>    ROLE_ARN: {REPLACE_YOUR_GITLAB_ROLE_ARN}<br>    ECS_CLUSTER: fastapi-app<br>    ECS_SERVICE: fastapi-app<br>    ECS_TASK_DEFINITION: fastapi-app<br>  before_script:<br>    - mkdir -p ~/.aws<br>    - echo &quot;${GITLAB_OIDC_TOKEN}&quot; &gt; /tmp/web_identity_token<br>    - echo -e &quot;[profile default]\nrole_arn=${ROLE_ARN}\nweb_identity_token_file=/tmp/web_identity_token&quot; &gt; ~/.aws/config<br>  script:<br>    - TASK_DEFINITION=$(aws ecs describe-task-definition --task-definition &quot;$ECS_TASK_DEFINITION&quot;)<br>    - NEW_TASK_DEFINTIION=$(echo &quot;$TASK_DEFINITION&quot; | python ./aws/update-ecs-task.py &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;)<br>    - aws ecs register-task-definition --cli-input-json &quot;$NEW_TASK_DEFINTIION&quot;;<br>    - aws ecs update-service --cluster $ECS_CLUSTER --service $ECS_SERVICE --task-definition $ECS_TASK_DEFINITION --force-new-deployment;<br><br></pre><p>2.<strong> Create </strong>./aws/update-ecs-task.py</p><p>Add a new script file to the aws folder of your project i.e update-ecs-task.py. This script will dynamically inject the currently docker tagged image inside the task definition and will give us back the updated task definition in the form of JSON.</p><p>This task definition will be used by aws ecs register-task-definition in the next command to register a new revision of the existing task i.e fastapi-app</p><p>Once a new task defintion is registered, this next command will force a new deployment on the service fastapi-app</p><pre>aws ecs update-service --cluster $ECS_CLUSTER --service $ECS_SERVICE --task-definition $ECS_TASK_DEFINITION --force-new-deployment;</pre><p>Commit and push your changes to GitLab. This will automatically trigger the CI/CD pipeline defined in .gitlab-ci.yml . First it will build the docker image from the ./docker/Dockerfile.prod in your project root directory. Then it will push that docker image to GitLab container registry.</p><p>If the build stage gets successfull, it will run the deploy stage. In the deploy stage, it will setup the required permissions based on the GitLab IAM role which we have set under variables as</p><pre>ROLE_ARN: rn:aws:iam::AWS_ACCOUNT_ID:role/GitLab</pre><p>Once the pipeline completes, access your FastAPI app by visiting the public DNS or Public IPV4 of your ECS task. Make sure to try accessing it without HTTPS i.e <a href="http://52.87.178.44/">http://52.87.178.44</a></p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/dockerization/tree/master/04.%20deploy-fastapi-app-to-ecs">dockerization/04. deploy-fastapi-app-to-ecs at master · BuildWithLal/dockerization</a></p><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311753e51a90" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/automate-fastapi-deployment-to-aws-ecs-with-gitlab-ci-311753e51a90">Automate FastAPI Deployment to AWS ECS with GitLab CI</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize FastAPI for Development and Production]]></title>
            <link>https://python.plainenglish.io/dockerize-fastapi-for-development-and-production-4a2adfd722f2?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a2adfd722f2</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 07:02:29 GMT</pubDate>
            <atom:updated>2024-12-02T17:42:14.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZoA30_eT-kkU2kB3_3jYA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@amiraaartistry?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Amira El Fohail</a> on <a href="https://unsplash.com/photos/a-large-amount-of-containers-are-stacked-together-xbSIYmuzY-o?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In this guide, we’ll go step-by-step through Dockerizing a FastAPI app for both development and production — making it easy to deploy, test, and scale with just a few commands. Let’s dive in…</p><h3>Project Directory Structure</h3><p>To keep things organized, we’ll set up our files as follows:</p><pre><br>fastapi-app<br><br>          ├── app # FastAPI app code<br>          ├── docker<br>                   ├── Dockerfile # development<br>                   ├── Dockerfile.prod<br>                   ├── entrypont.sh # development<br>                   ├── entrypoint.prod.sh          <br><br>          ├── docker-compose.yml # For local dev<br>          ├── requirements.txt<br>          ├── gunicorn.conf.py</pre><p>Each file has a specific purpose, and we’ll go over each of them step by step.</p><h3>Set Up the FastAPI Project</h3><ol><li><strong>Create Python Virtual Env</strong></li></ol><p>First create a directory for your project called fastapi-app. Switch to the project directory.</p><pre>mkdir fastapi-app<br><br>cd fastapi-app</pre><p>create and activate virtual environment using below commands.</p><pre>python -m venv .venv<br><br>source .venv/bin/activate</pre><p>Add requirements.txt for Python packages including FastAPI and Uvicorn.</p><pre>fastapi==0.115.5<br>uvicorn==0.32.0</pre><p>Install Dependencies from requirements.txt</p><pre>pip install -r requirements.txt</pre><p>Create folder for the FastAPI source code</p><pre>mkdir app</pre><p>Add main.py file to the app folder with the below script.</p><pre>from fastapi import FastAPI<br><br>app = FastAPI(<br>    title=&quot;Build With Lal&quot;,<br>    description=&quot;Ease your build!&quot;<br>)<br><br>@app.get(&quot;/&quot;)<br>async def home():<br>    return {&quot;success&quot;: True, &quot;message&quot;: &quot;Welcome to Build With Lal!&quot;}<br></pre><p>2. <strong>Run the App Locally</strong><br> Inside the root directory of the project, run this command</p><pre>uvicorn app.main:app --reload --port 8000</pre><p><strong>What is app.main:app?</strong></p><pre>app: FastAPI app source folder<br>main: main.py inside app folder<br>app: app variable inside app folder.</pre><p>You should see the app running at <a href="http://localhost:3000`">http://localhost:8000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*8p7Unwx4vZF82rNtcKUnsg.png" /></figure><h3>Dockerize for Local Development</h3><p>1. <strong>Add the Dockerfile</strong></p><p>In the root of the project directory, create a new folder docker and add a Dockerfile to that folder to create a containerized version of your app for local development.</p><p>./docker/Dockerfile</p><pre>FROM python:3.13-alpine<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br><br>RUN pip install -r requirements.txt<br><br>COPY ./app ./src<br><br>COPY ./docker/entrypoint.sh ./<br><br>RUN chmod +x entrypoint.sh<br><br>ENTRYPOINT [&quot;/bin/sh&quot;, &quot;/app/entrypoint.sh&quot;]</pre><p>The reason we are copying requirements.txt separately than the source code app using a separate COPY instructions is to not install packages repeatedly if anything gets change in our source code under app folder.</p><p>So this way if you make a change in source code and you re-build the docker image, it will resume building from the COPY ./app ./src instruction.</p><p>Packages should be re-installed only if there is a change in requirements.txt. But you’ll see later that we are completely restricting package installation to inside the docker container using docker volumes.</p><p><strong>2. Add entrypoint.sh</strong></p><p>Add an entrypoint.sh file to the docker folder to take care of starting FastAPI app using Uvicorn.</p><p>./docker/entrypoint.sh</p><pre>#!/bin/bash<br><br>cd ./src<br><br>echo &quot;Starting FastAPI application...&quot;<br><br>uvicorn main:app --host ${HOST:-0.0.0.0} --port ${APP_PORT:-8000} --reload</pre><p><strong>3. Add .env file</strong></p><p>Add a .env file in the the root directory to keep app’s level configurations and settings.</p><p>.env</p><pre>APP_PORT=8000</pre><p>4. <strong>Add docker-compose.yml</strong></p><p>Now, add docker-compose.yml in the root directory to simplify running Docker in development mode.</p><p>docker-compose.yml</p><pre>services:<br><br>  fastapi-app:<br>    container_name: fastapi-app<br>    image: fastapi-app<br>    build:<br>      context: .<br>      dockerfile: ./docker/Dockerfile <br>    ports:<br>      - &quot;${APP_PORT}:${APP_PORT}&quot;<br>    volumes:<br>      - ./app:/app/src<br>    env_file:<br>      - .env</pre><ul><li>- ./app:/app/src : This is a two way sync. Changes made on the host machine will be immediately reflected in container and vice-versa.</li></ul><p><strong>5. Skip Unnecessary Files and Folders from Docker Build</strong></p><p>Add a .dockerignore file in the root directory to skip on __pycache__, .git and .venv etc when passing content to the docker container.</p><p>.dockerignore</p><pre>__pycache__<br>*.pyc<br>.venv<br>Dockerfile<br>docker-compose.yml<br>.dockerignore<br>README.md<br>.git<br><br># add any other files and folders here</pre><p>6. <strong>Test the Setup Locally</strong></p><p>Run the following command to start your app in a Docker container</p><pre>docker compose up</pre><p>You should be able to access the app at <a href="http://localhost:3000`">http://localhost:8000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*8p7Unwx4vZF82rNtcKUnsg.png" /></figure><p>If you make any changes to the app, it should be auto-reloading inside the docker container managed by docker compose and you should see new updates immediately in the browser as you make any updates to the app.</p><h3>How do i install a new Python package?</h3><p>If you need to install a new package to your project from the host machine, try this command in a new terminal from the project root directory.</p><pre>docker compose exec -it fastapi-app pip install {PACKAGE_NAME}</pre><h3>Dockerize for Production</h3><p>Next, we’ll create a production-ready Dockerfile that’s updated for deployment to production by running a gunicorn server instead of uvicorn with multiple workers.</p><ol><li><strong>Add Dockerfile.prod</strong></li></ol><p>Add a new Dockerfile in the docker directory</p><p>./docker/Dockerfile.prod</p><pre>FROM python:3.13-alpine<br><br>WORKDIR /app<br><br>COPY ./requirements.txt ./<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>RUN pip install gunicorn==23.0.0<br><br>COPY ./app ./<br><br>COPY gunicorn.conf.py ./<br><br>COPY ./docker/entrypoint.prod.sh ./<br><br>RUN chmod +x entrypoint.prod.sh<br><br>ENTRYPOINT [&quot;/bin/sh&quot;, &quot;/app/entrypoint.prod.sh&quot;]</pre><p>This Dockerfile requires a gunicorn.conf.py and a separate entrypoint for production. Its always recommended to use Gunicorn in production to handle thousands of requests efficiently with multiple workers and utitlize max out of the CPUs.</p><p><strong>2. Add </strong><strong>gunicorn.conf.py</strong></p><p>Add a new python file in the root directory</p><p>gunicorn.conf.py</p><pre>import multiprocessing<br>import os<br><br># Bind the application to a specific IP and port<br>bind = f&quot;0.0.0.0:{os.getenv(&#39;APP_PORT&#39;, 8000)}&quot;<br><br># Number of worker processes (2 * CPUs + 1 is a common rule)<br>workers = multiprocessing.cpu_count() * 2 + 1<br><br># Worker class (recommended for FastAPI/ASGI apps)<br>worker_class = &quot;uvicorn.workers.UvicornWorker&quot;<br><br># Maximum number of requests a worker can handle before being restarted (to prevent memory leaks)<br>max_requests = 1000<br><br># random variation to the restart threshold for each worker, ensuring that not all workers restart at the exact same time<br>max_requests_jitter = 50<br><br># Logging<br>accesslog = &quot;-&quot;  # Standard output for access logs<br>errorlog = &quot;-&quot;   # Standard output for error logs<br>loglevel = &quot;info&quot;<br><br># Graceful timeout for worker shutdown<br>timeout = 30<br><br># Preload the application to reduce memory usage<br>preload_app = True<br><br># Enable keep-alive connections<br>keepalive = 120</pre><p><strong>3. Add </strong><strong>entrypoint.prod.sh</strong></p><p>Add a separate entrypoint for the production Dockerfile to start gunicorn server instead of uvicorn.</p><p>./docker/entrypoint.prod.sh</p><pre>#!/bin/bash<br><br>echo &quot;Starting FastAPI application...&quot;<br><br>gunicorn -c gunicorn.conf.py main:app</pre><p><strong>4. Test Production Docker Image Locally</strong></p><p>Build and run the production image locally to ensure everything looks good</p><pre>docker build -t fastapi-app-prod -f Dockerfile.prod .</pre><pre>docker run -it -p 8080:8000 fastapi-app-prod</pre><p>You should be able to access the app at <a href="http://localhost:8080/">http://localhost:8080</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*8p7Unwx4vZF82rNtcKUnsg.png" /></figure><p>Check the the number of workers started by the production container using gunicorn. All of these workers are ready to handle concurrent requests as they are received by gunicorn. Make sure to update gunicorn.conf.py to have a minimum number of workers up while there are no requests to serve and keep opening new workers on demand as requests are increasing a.k.a auto-scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcNsFTG8o7ahJwnkobs5dw.png" /></figure><blockquote>Any changes you make to the app will not be effective in this docker container as this is supposed to be deployed on production and not for local development unless you re-build and run.</blockquote><p>Now lets switch to prepare the ground for the <strong><em>FastAPI app in production</em></strong> in our next article by setting up AWS ECS and GitLab CI pipeline for automating deployment.</p><p><a href="https://aws.plainenglish.io/automate-fastapi-deployment-to-aws-ecs-with-gitlab-ci-311753e51a90">Automate FastAPI Deployment to AWS ECS with GitLab CI</a></p><p><strong>Source Code on GitHub</strong></p><p><a href="https://github.com/BuildWithLal/dockerization/tree/master/03.%20dockerize-fastapi-app">dockerization/03. dockerize-fastapi-app at master · BuildWithLal/dockerization</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDmLUO9M9EBQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDmLUO9M9EBQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDmLUO9M9EBQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e41e3dde8c033f50d8452282b9ac86af/href">https://medium.com/media/e41e3dde8c033f50d8452282b9ac86af/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a2adfd722f2" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/dockerize-fastapi-for-development-and-production-4a2adfd722f2">Dockerize FastAPI for Development and Production</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Security in GitLab CI: How to Set Up Dependency Scanning]]></title>
            <link>https://medium.com/@BuildWithLal/automating-security-in-gitlab-ci-how-to-set-up-dependency-scanning-d6f65c555b4c?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6f65c555b4c</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[dependencies]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 07:34:57 GMT</pubDate>
            <atom:updated>2024-11-18T08:06:51.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8O14EenDyxKN9_SvCOwmQ.jpeg" /><figcaption>Source: <a href="https://www.canva.com/design/DAGWXCbiMRI/hEO0RCG7HlsRTeK-D17ETA/edit?embeddedPage=home#">Syda Productions</a> on <a href="https://www.canva.com/">Canva.com</a></figcaption></figure><p>Dependency Scanning checks the external libraries and packages your code depends on for known vulnerabilities, including nested dependencies.</p><p>By running Dependency Scanning during development, you can detect vulnerabilities early in the pipeline and address them before changes are deployed to production. Once a scan is completed, GitLab shows the vulnerabilities in the merge request and saves a report into the job artifacts which you can download for further review.</p><h3>How analyzers are triggered</h3><p>GitLab triggers analyzers based on specific files in the repository, like a yarn.lock or a requirements.txt , up to two directory levels deep. Once a supported file is found, all dependencies including nested ones are analyzed for vulnerabilities.</p><h3>Enable the Dependency Scanning Analyzer</h3><p>Before enabling the analyzer, you need to make sure you’ve all of these ready.</p><ul><li>You must be using <strong>GitLab Ultimate Tier</strong> under GitLab.com, Self-managed or GitLab Dedicated</li><li>The test stage is required in the .gitlab-ci.yml file.</li><li>You need a GitLab Runner with the <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">docker</a> or kubernetes executor.</li></ul><p>To enable the analyzer, GitLab provides multiple options and you can select either of these based on your usecase:</p><ul><li>Enable Auto DevOps</li><li>Use a preconfigured Merge Request</li><li>Create a scan execution policy</li><li>Edit the .gitlab-ci.yml file manually</li></ul><p>In this guide, we’ll use the last option by editing .gitlab-ci.yml file manually to integrate Container scanning analyzer</p><h3>Update GitLab CI file to add Analyzer</h3><p>Go to your project in GitLab dashboard, Click on Pipeline Editor under the Build and add this simple snippet to your .gitlab-ci.yml</p><pre>include:<br>  - template: Jobs/Dependency-Scanning.gitlab-ci.yml</pre><p>This will add a predefined <a href="https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Jobs/Dependency-Scanning.gitlab-ci.yml">template</a> from GitLab into your CI file which will add a new job to the pipeline called gemnasium-dependency_scanning under the stage test .</p><p>Once you commit the above changes, a new pipeline should start running which will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*rW-vCCvgZbE-Fum0rM6Gcw.png" /></figure><p>What the gemnasium-python-dependency_scanning job does that, it will first download the scanning analyzer image from the GitLab registry.gitlab.com/security-products/gemnasium-python:5</p><p>Then it will run the command /analyzer run under its script section. /analyzer run is looking for a dependencies file under root directory and two level nested if it founds any.</p><p>Since we don’t have any depencies file yet, lets add one.</p><p>requirements.txt</p><pre>requests==2.19.1</pre><p>and update .gitlab-ci.yml as well</p><pre>include:<br>  - template: Jobs/Dependency-Scanning.gitlab-ci.yml<br><br><br>build:<br>    stage: build<br>    image: alpine<br>    script:<br>        - echo &quot;Build project&quot;</pre><p>We’ll test our scanning with a Python project where dependencies are managed by requirements.txt file. This specific version of requests library has some known vulnerabilities. Our files structure looks like this now.</p><pre>├── requirments.txt<br>├── .gitlab-ci.yml</pre><p>Lets commit these changes and see how the Analyzer scan this project for the vulnerabilities.</p><p>After committing the above changes, the newly run pipeline will look like this having a build job and a python-dependencies_scanning job</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*W6mAQmCQ9Nnn6alrfQd1qw.png" /></figure><p>The dependencies_scanning will only run if the build job succeeded as the test stage comes after build stage is successful.</p><p><strong>Scanning Analyzer output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICcGMkyOhHt72t8xWKI57g.png" /></figure><p>Dependency scanning outputs a report containing details of all vulnerabilities. The report is processed internally and the results are shown in the job logs. The report is also output as an artifact of the dependency scanning job, named gl-dependency-scanning-report.json</p><pre>{<br>  &quot;vulnerabilities&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Internationalized Domain Names in Applications (IDNA) vulnerable to denial of service from specially crafted inputs to idna.encode&quot;,<br>      &quot;description&quot;: &quot;A specially crafted argument to the `idna.encode()` function could consume significant resources. This may lead to a denial-of-service.&quot;,<br>      &quot;severity&quot;: &quot;High&quot;,<br>      &quot;solution&quot;: &quot;Upgrade to version 3.7 or above.&quot;,<br>      &quot;location&quot;: {<br>        &quot;file&quot;: &quot;requirements.txt&quot;,<br>        &quot;dependency&quot;: {<br>          &quot;package&quot;: {<br>            &quot;name&quot;: &quot;idna&quot;<br>          },<br>          &quot;version&quot;: &quot;2.7&quot;<br>        }<br>      }<br>      &quot;details&quot;: {<br>        &quot;vulnerable_package&quot;: {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;name&quot;: &quot;Vulnerable Package&quot;,<br>          &quot;value&quot;: &quot;idna:2.7&quot;<br>        }<br>      }<br>    }<br>  ],<br>  &quot;scan&quot;: {<br>    &quot;analyzer&quot;: {<br>      &quot;id&quot;: &quot;gemnasium-python&quot;,<br>      &quot;name&quot;: &quot;gemnasium-python&quot;,<br>      &quot;url&quot;: &quot;https://gitlab.com/gitlab-org/security-products/analyzers/gemnasium&quot;<br>    },<br>    &quot;scanner&quot;: {<br>      &quot;id&quot;: &quot;gemnasium-python&quot;,<br>      &quot;name&quot;: &quot;gemnasium-python&quot;,<br>      &quot;url&quot;: &quot;https://gitlab.com/gitlab-org/security-products/analyzers/gemnasium&quot;<br>    },<br>    &quot;type&quot;: &quot;dependency_scanning&quot;,<br>    &quot;status&quot;: &quot;success&quot;<br>  }<br>}</pre><h3>Fail Pipeline based on Scanner Vulnerabilities</h3><p>You might have noticed that no matter if the analyzer report low, medium or high serverity vulnerabilities, the dependency_scanning job is still marked as passed and the pipeline looks green and passed as well.</p><blockquote>Then what is the point with this dependencies scanning?</blockquote><p>As the named speaks itself! its the analyzer and its only reporting the vulnerabilities. GitLab does not provide a way to decide a pipeline’s status based on these vulnerabilities report but it does provide a JSON report saved into the pipeline artifacts.</p><p>Lets re-use the vulnerabilities json report and mark the pipeline either passed or failed if there are any high severity vulnerabilities in the report.</p><pre>include:<br>  - template: Jobs/Dependency-Scanning.gitlab-ci.yml<br><br><br>build:<br>    stage: build<br>    image: alpine<br>    script:<br>        - echo &quot;Build project&quot;<br><br>gemnasium-python-dependency_scanning:<br>    allow_failure: false # force pipeline to fail if this job fails<br><br>    before_script:<br>        - apt-get update -y &amp;&amp; apt-get install -y jq<br>  <br>    script:<br>        - /analyzer run<br>        - HIGH_SEVERITY_COUNT=$(jq &#39;.vulnerabilities | map(select(.severity==&quot;High&quot;)) | length&#39; gl-dependency-scanning-report.json )<br>        - &gt; <br>            if [[ $HIGH_SEVERITY_COUNT -gt 0 ]]<br>            then<br>              echo &quot;High severity found&quot;; exit 1<br>            else<br>              echo &quot;No High severity found&quot;<br>            fi<br>deploy:<br>    stage: deploy<br>    image: alpine<br>    script:<br>      - echo &quot;Deployed&quot;</pre><p>First we are adding allow_failure: false so the pipeline will fail in case this job fails.</p><p>Next we are installing <a href="https://jqlang.github.io/jq/">jq</a> under the before_script. <strong>jq</strong> is a lightweight and flexible command-line JSON processor</p><p>sudo apt-get update -y &amp;&amp; sudo apt-get install -y jq</p><p>Next, we are overriding the script part from the Scanner template. If you check <a href="https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Jobs/Dependency-Scanning.gitlab-ci.yml#L49">here</a> the template, script part is running /analyzer run command only.</p><p>So when overriding, we are first running the /analyzer run and then we are parsing the analyzer report file gl-dependency-scanning-report.json to find the count of high severity vulnerabilities.</p><p>At the last line of script we are just checking if there is any high severity vulnerability, we are exiting the script which will mark the job as failed and so the whole pipeline.</p><p>We are also adding a new job deploy in the deploy stage to make sure that the deploy stage won’t run in case the dependency_scanning job failed.</p><p>Since the dependency_scanning is under the test stage, the deploy stage never executes if the test stage fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV0yZ6FkPY7eE4FB8JwO5w.png" /></figure><p>So this way, you can easily decide whether to deploy to the staging or production by using the scanning analyzer.</p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/gitlab-in-docker/tree/master/11.%20scan-dependencies-in-gitlab-ci">gitlab-in-docker/11. scan-dependencies-in-gitlab-ci at master · BuildWithLal/gitlab-in-docker</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLfkho0rQ02c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLfkho0rQ02c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLfkho0rQ02c%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe360564a17fe3716bf0480834c62139/href">https://medium.com/media/fe360564a17fe3716bf0480834c62139/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6f65c555b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Next.js Deployment to AWS EC2 with GitLab CI]]></title>
            <link>https://aws.plainenglish.io/automate-next-js-deployment-to-aws-ec2-with-gitlab-ci-ba0c1459e09f?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba0c1459e09f</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[iam-roles]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 06:33:36 GMT</pubDate>
            <atom:updated>2024-11-22T07:18:54.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K7p-2rRSh2u6Hy7K-XCtQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@homaappliances?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Homa Appliances</a> on <a href="https://unsplash.com/photos/a-large-machine-in-a-large-building-pWUyHVJgLhg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Imagine pushing a single button and watching your code deploy itself to a server. No <em>manual steps </em>— just smooth, automated deployment from GitLab to AWS. If you’re managing multiple deployments or frequently updating your app, automated deployment is the recommended way.</p><p>In this article, we’ll cover exactly how to set up an automated CI/CD pipeline for a <a href="https://medium.com/@BuildWithLal/dockerize-next-js-app-for-local-development-and-production-76db292d6bff">Dockerized Next.js app</a>, all the way from setting up an AWS EC2 instance, IAM Roles and GitLab CI/CD.</p><p>In our <a href="https://medium.com/@BuildWithLal/dockerize-next-js-app-for-local-development-and-production-76db292d6bff">previous article</a>, we have already covered how to dockerize Next.js app for both local development and production so we’ll continue it from that production-ready Dockerfile.</p><p><a href="https://javascript.plainenglish.io/dockerize-next-js-app-for-local-development-and-production-76db292d6bff">Dockerize Next.JS app for Local development and Production</a></p><p>To keep things organized, we’ll set up our files as follows:</p><pre>nextjs-app<br><br>├── app # Next.js app code<br>├── Dockerfile # For local dev<br>├── Dockerfile.prod # Dockerfile for production<br>├── docker-compose.yml # For local dev<br>├── deploy-to-ec2.sh # Script for EC2 deployment<br>└── .gitlab-ci.yml # GitLab CI/CD configuration</pre><p>What we are going to cover:</p><ol><li>Set Up EC2 Instance</li><li>Install Docker and SSM Agent on EC2 Instance</li><li>Create IAM Roles for GitLab CI and SSM Agent</li><li>Create GitLab CI</li><li>Create Deployment Script</li></ol><h3>Set Up EC2 Instance</h3><p>We’ll deploy the app on an AWS EC2 instance with Docker installed. Please follow the steps below to have an EC2 instance up and ready to serve a dockerized Next.js app.</p><ul><li>Go to <a href="http://console.aws.amazon.com/ec2">AWS EC2</a> → Click on <strong>Launch Instance</strong></li><li>Give your instance a name nextjs-app</li><li>Select an OS Ubuntu → Select OS Image Ubuntu Server 24.04 Free Tier Eligible</li><li>Instance Type t2.micro</li><li>Select Allow SSH traffic from and select either a custom IP, Your IP or Anywhere</li><li>Select Allow HTTP traffic from the internet</li><li>Set Storage to 20 GiB gp3 → Click on Launch Instance</li><li>On the key pair popup, Click on Create new key pair</li><li>Give key pair a name nextjs-app</li><li>Keep rest of the things as default and click on Launch Instance</li></ul><blockquote>Hold ON for a while so your machine could up and run by AWS.</blockquote><p>Make sure the private .pem key is downloaded to your local machine.</p><p>While the instance is initializing, make sure that the EC2 instance has a Public IPv4 address attached.</p><h3>Install Docker on EC2 Instance</h3><p>Once your EC2 instance status is Running, open your terminal on local machine and switch to the directory where you have downloaded the private .pem key pair file. Run this command on you .pem keyfile to update the permissions.</p><pre>chmod 400 nextjs-app.pem</pre><p>Now Go to the EC2 dashboard, select your running instance and copy the Public IPv4 address . Run this command to SSH into EC2 instance</p><pre>ssh -i nextjs-app.pem ubuntu@54.226.179.65 # Replace EC2 instance IP here</pre><p>Once you are logged in to the EC2 instance. Run these commands to install and configure Docker.</p><pre>sudo apt-get update<br>sudo apt-get install ca-certificates curl</pre><pre>sudo install -m 0755 -d /etc/apt/keyrings</pre><pre>sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc</pre><pre>sudo chmod a+r /etc/apt/keyrings/docker.asc<br></pre><pre># Add the repository to Apt sources:<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \<br>  $(. /etc/os-release &amp;&amp; echo &quot;$VERSION_CODENAME&quot;) stable&quot; | \<br>  sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><pre>sudo apt-get update</pre><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><pre>sudo groupadd docker</pre><pre>sudo usermod -aG docker $USER</pre><pre>newgrp docker</pre><p>Run a demo container to ensure we can spin up containers using newly installed docker</p><pre>docker run --rm hello-world</pre><p>You should get a Hello from Docker! message.</p><h3><strong>Install SSM Agent on EC2 instance</strong></h3><p>To deploy and run containers on EC2 from inside the GitLab pipeline, we need to first SSH into our EC2 instance inside our GitLab pipeline.</p><p>We’ll not use any AWS access key and secret key in our GitLab CI but instead we’ll SSH to EC2 instance using <strong>AWS SSM agent</strong> from our pipeline which is the safest and recommended way to SSH into EC2 from external services.</p><p>Run these commands to setup SSM agent on EC2. Ignore any messages if the agent is already installed.</p><pre>sudo snap install amazon-ssm-agent<br><br>sudo systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service<br><br>sudo systemctl status snap.amazon-ssm-agent.amazon-ssm-agent.service</pre><p>By running the last command, it should print the status message as Active: active (running)This will make sure that the SSM agent is active and running.</p><h3>AWS IAM Roles for GitLab CI</h3><h4><strong>1. IAM Identify Provider</strong></h4><p>The first thing we need to do in terms of permissions, is to setup an IAM <strong>identity provider</strong>.</p><p>Identity provider (Idp) is used to manage your user identities outside of AWS, but grant the user permissions to use AWS resources in your account. This is exactly what we need to do, stay in the GitLab but give access to our EC2 instance in AWS without exposing any secret keys to GitLab.</p><p>Go <strong>AWS IAM → Identity providers → Add Provider</strong></p><p>On the next screen, select <strong>OpenID Connect</strong></p><p>Set both <strong>Provider URL</strong> and <strong>Audience</strong> to <a href="https://gitlab.com/">https://gitlab.com</a></p><h4><strong>2. IAM Role For Identity Provider</strong></h4><p>Go to <strong>AWS IAM → Roles → Create Role</strong></p><p>On the next screen, select <strong>Web Identity</strong></p><p>Under the Web identity<strong>, </strong>Select GitLab as Identity Provider and Audience</p><p>On the permissions screen, Attach <strong>AmazonEC2FullAccess</strong> and <strong>AmazonSSMFullAccess</strong></p><p>Give the role a name i.e <strong>GitLab</strong></p><h4>3. IAM Role For SSM Agent</h4><p>Go to <strong>AWS IAM → Roles → Create Role</strong></p><p>On the next screen, select <strong>AWS Service</strong></p><p>Under the AWS Service<strong>, </strong>Select EC2</p><p>On the permissions screen, Attach <strong>AmazonSSMManagedInstanceCore</strong></p><p>Give the role a name i.e <strong>GitLabSSHViaSSMAgent</strong></p><h4>4. Attach SSM Agent Role to EC2 Instance</h4><p>For the SSM Agent to work with EC2 instance, we need to attach our IAM Role i.e GitLabSSHViaSSMAgent<strong> </strong>to EC2 instance.</p><p>Go to <strong>EC2 → Instances → Select Your Instance → Click on Actions → Security → Modify IAM Role → Select IAM Role (</strong>GitLabSSHViaSSMAgent<strong>) → Update IAM Role</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0stuKP4dliadbpB3ninww.png" /></figure><blockquote>I promise we’re done with all the IAM stuff 😎</blockquote><h3>Create the GitLab CI/CD Pipeline</h3><p>1. <strong>Add </strong><strong>.gitlab-ci.yml</strong></p><p>Add .gitlab-ci.yml to your GitLab project root directory.</p><p>.gitlab-ci.yml</p><pre><br>build:<br>  stage: build<br>  image: docker<br>  services:<br>    - docker:27.2.0-dind<br>  variables:<br>    DOCKER_HOST: tcp://docker:2376<br>    DOCKER_TLS_CERTDIR: &quot;/certs&quot;<br>  script:<br>    - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin<br>    - docker build -t &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot; -f Dockerfile.prod .<br>    - docker push &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;```<br><br>deploy:<br>  stage: deploy<br>  image: registry.gitlab.com/gitlab-org/cloud-deploy/aws-base:latest<br><br>  id_tokens:<br>    GITLAB_OIDC_TOKEN:<br>      aud: https://gitlab.com<br><br>  variables:<br>    AWS_DEFAULT_REGION: us-east-1<br>    ROLE_ARN: arn:aws:iam::379406586218:role/GitLab<br><br>  before_script:<br>    - curl &quot;https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb&quot; -o &quot;session-manager-plugin.deb&quot;<br>    - dpkg -i session-manager-plugin.deb<br>    - session-manager-plugin --version<br>    - apt-get update -y &amp;&amp; apt-get install -y expect<br>    - mkdir -p ~/.aws<br>    - echo &quot;${GITLAB_OIDC_TOKEN}&quot; &gt; /tmp/web_identity_token<br>    - echo -e &quot;[profile default]\nrole_arn=${ROLE_ARN}\nweb_identity_token_file=/tmp/web_identity_token&quot; &gt; ~/.aws/config<br><br>  script:<br>    - cat ~/.aws/config<br>    - aws sts get-caller-identity<br>    - chmod +x deploy-to-ec2.sh<br>    - ./deploy-to-ec2.sh</pre><p>2.<strong> Create</strong><strong> deploy-to-ec2.sh</strong></p><p>Add a new script file to the root of your project directory i.e deploy-to-ec2.sh. This script will SSH into the EC2 instance using SSM agent and will deploy the Dockerized Next.js app. If there is already a running container, it will first stop it and then re-run a new container with same name and same set of ports.</p><pre>INSTANCE_ID=&quot;i-028b04a54d22eddbf&quot; # Replace your EC2 Instance ID<br><br>APP_CONTAINER_NAME=&quot;nextjs-app&quot; # Container name inside EC2 instance<br><br># this should match to whatever your registry URL is for the docker image<br>APP_CONTAINER_IMAGE=&quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;<br><br>DOCKER_LOGIN_COMMAND=&quot;echo $CI_REGISTRY_PASSWORD | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin&quot;<br>DOCKER_PULL_COMMAND=&quot;docker pull $APP_CONTAINER_IMAGE&quot;<br><br># Single-line CONTAINER_STOP_COMMAND to avoid parsing errors<br>CONTAINER_STOP_COMMAND=&quot;if [ \$(docker ps -q -f name=$APP_CONTAINER_NAME) ]; then docker stop $APP_CONTAINER_NAME &amp;&amp; docker rm $APP_CONTAINER_NAME; if [ \$? -eq 0 ]; then echo &#39;Container stopped successfully.&#39;; else echo &#39;Failed to stop the container.&#39;; exit 1; fi; else echo &#39;Container $APP_CONTAINER_NAME is not running. Skipping stop command.&#39;; fi&quot;<br>CONTAINER_START_COMMAND=&quot;docker run -d --restart unless-stopped -p 80:3000 --name $APP_CONTAINER_NAME $APP_CONTAINER_IMAGE&quot;<br><br># Send the Docker command to the EC2 instance<br>COMMAND_ID=$(aws ssm send-command \<br>    --document-name &quot;AWS-RunShellScript&quot; \<br>    --targets &quot;Key=instanceIds,Values=$INSTANCE_ID&quot; \<br>    --parameters commands=&quot;[\&quot;$DOCKER_LOGIN_COMMAND\&quot;, \&quot;$DOCKER_PULL_COMMAND\&quot;, \&quot;$CONTAINER_STOP_COMMAND\&quot;, \&quot;$CONTAINER_START_COMMAND\&quot;]&quot; \<br>    --query &quot;Command.CommandId&quot; \<br>    --output text)<br><br>echo &quot;Command sent. Command ID: $COMMAND_ID&quot;<br><br># Wait for the command to complete<br>while true; do<br>    STATUS=$(aws ssm list-command-invocations \<br>        --command-id &quot;$COMMAND_ID&quot; \<br>        --details \<br>        --query &quot;CommandInvocations[0].Status&quot; \<br>        --output text)<br>    echo &quot;Current Status: $STATUS&quot;<br>    if [[ &quot;$STATUS&quot; == &quot;Success&quot; || &quot;$STATUS&quot; == &quot;Failed&quot; || &quot;$STATUS&quot; == &quot;TimedOut&quot; || &quot;$STATUS&quot; == &quot;Cancelled&quot; ]]; then<br>        break<br>    fi<br>    sleep 2  # Wait for a few seconds before checking again<br>done<br><br># Get the output of the command<br>OUTPUT=$(aws ssm list-command-invocations \<br>    --command-id &quot;$COMMAND_ID&quot; \<br>    --details \<br>    --query &quot;CommandInvocations[0].CommandPlugins[0].Output&quot; \<br>    --output text)<br># Print the final output<br><br>echo &quot;Final Output:&quot;<br>echo &quot;$OUTPUT&quot;<br><br># Check if the command was successful<br>if [[ &quot;$STATUS&quot; == &quot;Success&quot; ]]; then<br>    echo &quot;Docker command executed successfully.&quot;<br>    exit 0  # Success<br>else<br>    echo &quot;Docker command failed with status: $STATUS&quot;<br>    exit 1  # Fail<br>fi</pre><h3>Trigger the CI/CD Pipeline</h3><p>Commit and push your changes to GitLab. This will automatically trigger the CI/CD pipeline defined in .gitlab-ci.yml . First it will build the docker image from the Dockerfile.prod in your project root directory. Then it will push that docker image to GitLab container registry.</p><p>If the build stage gets successfull, it will run the deploy stage. In the deploy stage, first download and install the Session Manager Plugin so AWS CLI can start session to EC2 instances. Next it will setup the required permissions based on the GitLab IAM role which we have set under variables as ROLE_ARN: rn:aws:iam::379406586218:role/GitLab</p><p>At the end, it will run ./deploy-to-ec2.sh script where it will first stop the running container on EC2 and then run a new container for the app.</p><p>Once the pipeline completes, access your Next.js app by visiting the public DNS or Public IPV4 of your EC2 instance. Make sure to try accessing it without HTTPS i.e <a href="http://52.87.178.44/">http://52.87.178.44</a></p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/dockerization/tree/master/02.%20deploy-nextjs-app-to-ec2">dockerization/02. deploy-nextjs-app-to-ec2 at master · BuildWithLal/dockerization</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FaDnqn0tZhv0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DaDnqn0tZhv0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FaDnqn0tZhv0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/feea66152d55fee1de2343e5d0a4f0ea/href">https://medium.com/media/feea66152d55fee1de2343e5d0a4f0ea/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba0c1459e09f" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/automate-next-js-deployment-to-aws-ec2-with-gitlab-ci-ba0c1459e09f">Automate Next.js Deployment to AWS EC2 with GitLab CI</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize Next.JS app for Local development and Production]]></title>
            <link>https://javascript.plainenglish.io/dockerize-next-js-app-for-local-development-and-production-76db292d6bff?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/76db292d6bff</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Wed, 06 Nov 2024 10:02:08 GMT</pubDate>
            <atom:updated>2024-11-17T05:38:39.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dockerize Next.js app for Development and Production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6w2ebATbrP5G2vPWKLMIKg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jonassmith?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jonas Smith</a> on <a href="https://unsplash.com/photos/pile-of-colorful-intermodal-containers-aL6tG-j-E4Y?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In this guide, we’ll go step-by-step through Dockerizing a Next.js app for both local development and production — making it easy to deploy, test, and scale with just a few commands. Let’s dive in…</p><h3>Project Directory Structure</h3><p>To keep things organized, we’ll set up our files as follows:</p><pre><br>nextjs-app<br><br>├── app # Next.js app code<br>├── Dockerfile # For local dev<br>├── Dockerfile.prod # For production<br>├── docker-compose.yml # For local dev<br>├── .dockerignore<br>├── .env</pre><p>Each file has a specific purpose, and we’ll go over each of them step by step.</p><h3>Set Up the Next.js Project</h3><ol><li><strong>Initialize the Project</strong></li></ol><p>First create a directory for your project called nextjs-app. Switch to the project directory and create the Next.js app using below commands.</p><pre><br>mkdir nextjs-app<br><br>cd nextjs-app<br><br>npx create-next-app@latest</pre><p>This will ask you some questions as you can see in the screenshot. Just keep hitting <strong>Enter</strong> in case you don’t have any context and your project will configured with defaults.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*10d7DkQStIv-yyHXY3l1hA.png" /></figure><p>After a few minutes, your app should be created and you’ll be good to start running it. Notice that we have named our Next.js project as app . So actual source code will be inside app folder while anything related to docker will be in the root directory.</p><p>2. <strong>Run the App Locally</strong><br> Inside the app directory (nextjs-app/app), start the Next.js app to ensure it’s working</p><pre><br>cd app<br><br>yarn dev</pre><p>You should see the app running at <a href="http://localhost:3000`">http://localhost:3000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*4Hqe5SBHQyJzp21Qb-3Bfw.png" /></figure><h3>Dockerize for Local Development</h3><p>1. <strong>Add the Dockerfile</strong></p><p>In the root of the project directory, add a Dockerfile to create a containerized version of your app for local development.</p><p>Dockerfile</p><pre>FROM node:22.11.0-alpine<br><br>WORKDIR /app<br><br>COPY ./app/package.json ./app/yarn.lock* ./<br><br>RUN yarn install<br><br>COPY ./app .<br><br>CMD [&quot;yarn&quot;, &quot;dev&quot;]</pre><p>The reason we are copying package.json and yarn.lock separately than the source code app using two separate COPY instructions is to not install packages repeatedly if anything gets change in our source code.</p><p>So this way if you make a change in source code and you re-build the docker image, it will resume building from the COPY ./app . instruction.</p><p>Packages should be re-installed only if there is a change in package.json or yarn.lock . But you’ll see later that we completely restricting package installation to inside the docker container using docker volumes.</p><p>2. <strong>Add </strong><strong>.env file</strong></p><p>Add a .env file to keep app’s level configurations and settings.</p><p>.env</p><pre>APP_PORT=3000</pre><p>3. <strong>Add </strong><strong>docker-compose.yml</strong></p><p>Now, add docker-compose.yml to simplify running Docker in development mode.</p><p>docker-compose.yml</p><pre>version: &#39;3.8&#39;<br>services:<br><br>  nextjs-app:<br>    image: nextjs-app<br>    container_name: nextjs-app<br>    build:<br>      context: .<br>    ports:<br>      - &#39;${APP_PORT}:${APP_PORT}&#39;<br>    volumes:<br>      - ./app:/app<br>      - node_modules:/app/node_modules # managed by docker. Restrict local yarn to get access<br>      - build:/app/.next # managed by docker. Restrict local yarn to get access<br>    env_file:<br>      - .env<br><br><br>volumes:<br>  node_modules:<br>  build:</pre><ul><li>- ./app:/app this is a two way sync. Changes made on the host machine will be immediately reflected in container and vice-versa.</li><li>node_modules:/app/node_modules Managed by docker. Restrict local yarn to get access to avoid getting conflicts between host yarn and container yarn</li><li>build:/app/.nextManaged by docker. Restrict local yarn to get access to avoid getting conflicts between host yarn and container yarn</li></ul><p><strong>4. Skip Unnecessary Files and Folders from Docker Build</strong></p><p>Add a .dockerignore file to skip on node_modules, .git and .next etc when passing content to the docker container.</p><p>.dockerignore</p><pre>node_modules<br>.next<br>.git<br><br># add any other files and folders here</pre><p>5. <strong>Test the Setup Locally</strong></p><p>Run the following command to start your app in a Docker container</p><pre>docker compose up</pre><p>You should be able to access the app at <a href="http://localhost:3000`">http://localhost:3000</a></p><p>If you make any changes to the app, it should be auto-reloading inside the docker container managed by docker compose and you should see new updates immediately in the browser as you make any updates to the app.</p><h3>How do i install a new NodeJS package?</h3><p>Since we have restricted the node_modules folder to be accessible from the docker container only, if you need to install a new package to your project from the host machine, try this command in a new terminal from the project root directory.</p><pre>docker compose exec -it nextjs-app yarn add {PACKAGE_NAME}</pre><h3>Dockerize for Production</h3><p>Next, we’ll create a production-ready Dockerfile that’s optimized for deployment but before that we need to make a minor change to our next.config.js file. Make sure you set the output to standalone</p><pre>const nextConfig: NextConfig = {<br>  output: &#39;standalone&#39;<br>};</pre><p>After running the yarn build , .next/standalone folder will have just the essential files and node_modules needed for production but don’t worry we’ll take care of this in production Dockerfile next.</p><pre>.next<br>    ├── standalone<br>    │   ├── node_modules<br>    │   ├── .next<br>    │   ├── .env<br>    │   ├── server.js<br>    │   └── package.json</pre><p>1. <strong>Add </strong><strong>Dockerfile.prod</strong></p><p>Dockerfile.prod</p><pre>FROM node:22.11.0-alpine AS base<br><br>###################################################<br># setup docker image to install all node packages #<br>###################################################<br><br>FROM base AS dependencies<br><br>WORKDIR /app<br>COPY ./app/package.json ./app/yarn.lock* ./<br>RUN yarn install<br><br><br>########################################<br># setup docker image for next.js build #<br>########################################<br><br>FROM base AS build<br><br>WORKDIR /app<br>COPY --from=dependencies /app/node_modules ./node_modules<br>COPY ./app .<br><br>ENV NEXT_TELEMETRY_DISABLED=1<br><br>RUN yarn run build<br><br>############################################################<br># setup docker image to hold build, static and run the app #<br>############################################################<br><br>FROM base AS runner<br>WORKDIR /app<br><br>ENV NODE_ENV=production \<br>    NEXT_TELEMETRY_DISABLED=1 \<br>    HOSTNAME=&quot;0.0.0.0&quot;<br><br>COPY --from=build /app/public ./public<br><br>RUN mkdir .next<br><br>COPY --from=build /app/.next/standalone ./<br>COPY --from=build /app/.next/static ./.next/static<br><br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>2. <strong>Test Production Docker Image Locally</strong></p><p>Build and run the production image locally to ensure everything looks good</p><pre><br>docker build -t nextjs-app-prod -f Dockerfile.prod .<br><br>docker run -it -p 3000:3000 nextjs-app-prod</pre><p>You should be able to access the app at <a href="http://localhost:3000`">http://localhost:3000</a></p><p>Check the the difference between Docker image size for local and production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*9154yBh3JupHHRTeLxd-DQ.png" /></figure><blockquote>Any changes you make to the app will not be effective in this docker container as this is supposed to be deployed on production and not for local development unless you re-build and run.</blockquote><p>Now lets switch to prepare the ground for the <strong><em>NextJS in production</em></strong> in our next article by setting up AWS EC2 and GitLab CI pipeline for automating deployment.</p><p><a href="https://medium.com/@BuildWithLal/automate-next-js-deployment-to-aws-ec2-with-gitlab-ci-ba0c1459e09f">Automate Next.js Deployment to AWS EC2 with GitLab CI</a></p><p><strong>Source Code on GitHub</strong></p><p><a href="https://github.com/BuildWithLal/dockerization/tree/master/01.%20dockerize-nextjs-app">dockerization/01. dockerize-nextjs-app at master · BuildWithLal/dockerization</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FucTmWale9SI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DucTmWale9SI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FucTmWale9SI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2906cc9dfc34042429c3e1b646965fd6/href">https://medium.com/media/2906cc9dfc34042429c3e1b646965fd6/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76db292d6bff" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/dockerize-next-js-app-for-local-development-and-production-76db292d6bff">Dockerize Next.JS app for Local development and Production</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Security in GitLab CI: How to Set Up Container Scanning]]></title>
            <link>https://medium.com/@BuildWithLal/automating-security-in-gitlab-ci-how-to-set-up-container-scanning-9cdc69934659?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdc69934659</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[container-security]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[security-vulnerabilities]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 09:02:17 GMT</pubDate>
            <atom:updated>2024-11-13T17:58:28.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOfa2Lga7rmq27oUbck0eQ.jpeg" /><figcaption>Source: Blue Planet Studio@canva.com</figcaption></figure><p>Container scanning is a way to check for security issues in the external dependencies your code depends on, like libraries and packages you didn’t write. Your application’s Docker image may be based on Docker images that contain known vulnerabilities. GitLab uses <a href="https://github.com/aquasecurity/trivy">Trivy</a> to scan containers for vulnerabilities.</p><p>Once a scan is completed, GitLab shows the vulnerabilities in the merge request and saves a report into the job artifacts which you can download for further review.</p><h3>Enable the Container Scanning Analyzer</h3><p>Before enabling the analyzer, you need to make sure you’ve all of these ready.</p><ul><li>The test stage is required in the .gitlab-ci.yml file.</li><li>You need a GitLab Runner with the <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">docker</a> or kubernetes executor.</li><li>Build and push the Docker image to your project’s <a href="https://medium.com/@BuildWithLal/setup-gitlab-container-registry-gitlab-managed-bbda71b3aef4">container registry</a>.</li><li>If you’re using a third-party container registry, you need to provide authentication credentials through the CS_REGISTRY_USER and CS_REGISTRY_PASSWORD CI variables.</li></ul><p>To enable the analyzer, GitLab provides multiple options and you can select either of these based on your usecase:</p><ul><li>Enable Auto DevOps</li><li>Use a preconfigured Merge Request</li><li>Create a scan execution policy</li><li>Edit the .gitlab-ci.yml file manually</li></ul><p>In this guide, we’ll use the last option by editing .gitlab-ci.yml file manually to integrate Container scanning analyzer</p><h3>Update GitLab CI file to add Analyzer</h3><p>Go to your project in GitLab dashboard, Click on Pipeline Editor under the Build and add this simple snippet to your .gitlab-ci.yml</p><pre>include:<br>  - template: Jobs/Container-Scanning.gitlab-ci.yml</pre><p>This will add a predefined <a href="https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Jobs/Container-Scanning.gitlab-ci.yml">template</a> from GitLab into your CI file which will add a new job to the pipeline called container_scanning under the stage test .</p><p>Once you commit the above changes, a new pipeline should start running which will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*qLNtuoK3--9DiEeMf4d8ew.png" /></figure><p>What the container_scanning job does that, it will first download the scanning analyzer image from the GitLab registry.gitlab.com/security-products/container-scanning.</p><p>Then it will run the command gtcs scan under its script section. gtcs scan is looking for a docker image to be scanned under the container registry for this same project i.e {REGISTRY_URL}/{USER}/{REPOSTIRY}/{DEFAULT_BRANCH}:{COMMIT_SHA}</p><p>I am running this container scanning job under my project build-with-lal and since i am not pushing the docker image to container registry (localhost:5001) before this scanning job, it fails and throws this message</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4aj9QHx-q6RI3xO5829Ng.png" /></figure><p>Lets add the build stage where we’ll build our docker image from the Dockerfile inside the project’s root directory and then we’ll push that docker image to the project’s container registry.</p><p><strong>Dockerfile</strong></p><pre>FROM python:3.10-alpine<br><br>RUN python --version</pre><p><strong>.gitlab-ci.yml</strong></p><pre>include:<br>  - template: Jobs/Container-Scanning.gitlab-ci.yml<br><br>build:<br>    stage: build<br>    image: docker:latest<br>    script:<br>        - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin<br>        - docker build -t &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot; .<br>        - docker push &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;</pre><p>The build stage will build the docker image and will push it to the project’s container registry under the URL</p><pre>localhost:5001/root/build-with-lal:4bf5d7b5</pre><p>After commiting the above changes, the newly run pipeline will look like this having a build job and a container_scanning job</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcJ_mE94x7MRFdF56fMoUw.png" /></figure><p>The container_scanning will only run if the build job succeeded as the test stage comes after build stage is successful. But you’ll see that container_scanning still fails because its still looking for the docker image on a different URL than where we have pushed our docker image in build stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYDV10O8aUybOSSHSGHxPQ.png" /></figure><p>As mentioned in the above screenshot, to change the image being scanned we can use CS_IMAGE environment variable under the container_scanning job. So lets override this variable as shown below.</p><pre>include:<br>    - template: Jobs/Container-Scanning.gitlab-ci.yml<br><br>container_scanning:<br>    before_script:<br>        - export CS_IMAGE=&quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;<br><br>build:<br>    stage: build<br>    image: docker:latest<br>    script:<br>        - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin<br>        - docker build -t &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot; .<br>        - docker push &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;</pre><p>The reason we are overriding CS_IMAGE under before_script and not under variables is that, we cannot manipulate string under variables. Since we are slicing commit tag to first 8 chars i.e ${CI_COMMIT_SHA:0:8} when building and pushing docker image to registry, we need that same sliced tag when referencing that image anywhere.</p><p>Now you should have both build and container_scanning job passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*dMPoY1NMYCXrhBZHEisCIA.png" /></figure><p><strong>Scanning Analyzer output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywgPM4P78rVp_pN7hMuZsg.png" /></figure><p>Analyzer has reported some vulnerabilities with low severity.</p><h3>Change Severity Threshold</h3><p>By default, the Analyzer will report all of the vulnerabilities including Low, Medium and High severity.</p><p>If you want to force Analyzer to report only Medium or High vulnerabilities, you can override the setting under variables as below.</p><pre>container_scanning:<br><br>    variables:<br>        CS_SEVERITY_THRESHOLD: &#39;medium&#39; # low, medium, high<br><br>    before_script:<br>        - export CS_IMAGE=&quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;</pre><p><strong>CS_SEVERITY_THRESHOLD: ‘low’</strong></p><p>This will report all vulnerabilities including low, medium and high severity.</p><p><strong>CS_SEVERITY_THRESHOLD: ‘medium&#39;</strong></p><p>This will skip vulnerabilities with low severity and will report medium and high only</p><p><strong>CS_SEVERITY_THRESHOLD: ‘high’</strong></p><p>This will skip vulnerabilities with low and medium severity and will report high only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1wmPt5gAJwQGaiFTzU41w.png" /></figure><p>Since we have low serverity vulnerabilities only, this time the analyzer has not reported any because we have forced it to report any vulnerabilities with medium or above serverity.</p><h3><strong>Scanning Log Level</strong></h3><p>By default, the scanner log level is set to info but we can override this under the job variables as below.</p><pre>container_scanning:<br><br>    variables:<br>        CS_SEVERITY_THRESHOLD: &#39;medium&#39; # low, medium, high<br>        SECURE_LOG_LEVEL: &#39;debug&#39; # debug, info, warn, error, fatal<br><br>    before_script:<br>        - export CS_IMAGE=&quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;</pre><h3>Fail Pipeline based on Scanner Vulnerabilities</h3><p>You might have noticed that no matter if the analyzer report low, medium or high serverity vulnerabilities, the container_scanning job is still marked as passed and the pipeline looks green and passed as well.</p><blockquote>Then what is the point with this container scanning?</blockquote><p>As the named speaks itself! its the analyzer and its only reporting the vulnerabilities. GitLab does not provide a way to decide a pipeline’s status based on these vulnerabilities report but it does provide a JSON report saved into the pipeline artifacts.</p><p>Lets re-use the vulnerabilities json report and mark the pipeline either passed or failed if there are any high severity vulnerabilities in the report.</p><pre>container_scanning:<br>    allow_failure: false # force pipeline to fail if this job fails<br>    variables:<br>        CS_SEVERITY_THRESHOLD: &#39;medium&#39; # low, medium, high<br>        SECURE_LOG_LEVEL: &#39;debug&#39; # debug, info, warn, error, fatal<br><br>    before_script:<br>        - sudo apt-get update -y &amp;&amp; sudo apt-get install -y jq<br>        - export CS_IMAGE=&quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;<br>  <br>    script:<br>        - gtcs scan<br>        - HIGH_SEVERITY_COUNT=$(jq &#39;.vulnerabilities | map(select(.severity==&quot;High&quot;)) | length&#39; gl-container-scanning-report.json )<br>        - &gt; <br>            if [[ $HIGH_SEVERITY_COUNT -gt 0 ]]<br>            then<br>              echo &quot;High severity found&quot;; exit 1<br>            else<br>              echo &quot;No High severity found&quot;<br>            fi<br><br>deploy:<br>    stage: deploy<br>    image: alpine<br>    script:<br>      - echo &quot;Deployed&quot;<br></pre><p>First we are adding allow_failure: false so the pipeline will fail in case this job fails.</p><p>Next we are installing <a href="https://jqlang.github.io/jq/">jq</a> under the before_script. <strong>jq</strong> is a lightweight and flexible command-line JSON processor</p><p>sudo apt-get update -y &amp;&amp; sudo apt-get install -y jq</p><p>Next, we are overriding the script part from the Scanner template. If you check <a href="https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Jobs/Container-Scanning.gitlab-ci.yml#L47">here</a> the template, script part is running gtcs scan command only.</p><p>So when overriding, we are first running the gtcs scan and then we are parsing the analyzer report file gl-container-scanning-report.json to find the count of high severity vulnerabilities.</p><p>At the last line of script we are just checking if there is any high severity vulnerability, we are exiting the script which will mark the job as failed and so the whole pipeline.</p><p>We are also adding a new job deploy in the deploy stage to make sure that the deploy stage won’t run in case the container_scanning job failed.</p><p>Since the container_scanning is under the test stage, the deploy stage never executes if the test stage fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tWLVvOrn3Lv3bJkmsD-QLw.png" /></figure><p>So this way, you can easily decide whether to deploy or not, your new docker image to the staging or production by using the scanning analyzer.</p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/gitlab-in-docker/tree/master/10.%20scan-container-images-in-registry">gitlab-in-docker/10. scan-container-images-in-registry at master · BuildWithLal/gitlab-in-docker</a></p><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiC6DLyJpzeM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiC6DLyJpzeM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiC6DLyJpzeM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/424acf9ab6a51530a52ca5ec6a55c801/href">https://medium.com/media/424acf9ab6a51530a52ca5ec6a55c801/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdc69934659" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build AI Powered Chatbot using Chainlit, OpenAI and Literal AI]]></title>
            <link>https://ai.plainenglish.io/build-ai-powered-chatbot-using-chainlint-openai-and-literal-ai-a7ee6cdf6163?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7ee6cdf6163</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chainlit]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[openai-chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 09:27:46 GMT</pubDate>
            <atom:updated>2024-11-25T07:21:10.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuGLNCYo74T4FDDL_WYKLg.jpeg" /><figcaption>Source: canva.com</figcaption></figure><h3>Why Build AI-Powered Chatbots?</h3><p>AI-powered chatbots are changing the way businesses interact with their customers. They can handle repetitive tasks like answering common questions, helping with bookings, and product recommendations, all in real-time. They work 24/7, giving quick, personalized support to customers while helping save time and money.</p><h3>What is Chainlit?</h3><p>Chainlit is a tool that makes it easy to build AI powered chatbots that can have smart conversations. It’s designed to work smoothly with AI models like OpenAI’s GPT, helping you create chatbots that feel more natural and human. Here are some cool features of Chainlit:</p><ul><li><strong>Easy Interface:</strong> Quickly create chat interfaces that are simple and user-friendly with support for extension.</li><li><strong>Integrations:</strong> Plug directly into any of these frameworks and LLMs for smart, AI-powered conversations.</li></ul><blockquote>FastAPI, Mistral AI, OpenAI, LangChain, Llama Index, LiteLLM, Haystack, Embedchain, vLLM, LMStudio, HuggingFace</blockquote><ul><li><strong>Handle Multiple Inputs:</strong> It supports not just text but also file uploads and other user interactions.</li><li><strong>Conversation Tracking: </strong>Keeps track of chats so users can pick up where they left off. Keep conversations persistent using <a href="https://literalai.com/">LiteralAI</a>, <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> or <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a></li><li><strong>Manage Chats:</strong> Users can rename and manage their conversation threads easily.</li><li><strong>User Login: </strong>Supports Google, GitLab, Auth0, Azure Directory and many more authentication backends for easy access.</li><li><strong>Platforms:</strong></li></ul><blockquote>Web App, Copilot, API, React, Teams, Slack, Discord</blockquote><p>Now as we know why AI Powered chatbots are important and what tools do we have to build it. Lets start building it by making a sample chatbot using <strong>Python</strong>, <strong>Chainlit</strong>, <strong>OpenAI</strong> and <strong>LiteralAI</strong>. We’ll call this chatbot <strong>DineBot</strong> since it will try to help restaurants by taking their orders and dealing with customers.</p><h3>Set Up Python Environment for the Chatbot</h3><p>Lets create a directory for the DineBot.</p><pre>mkdir dinebot</pre><p>Make sure Python is installed (version 3.10+ is recommended). Then, create a virtual environment to keep things organized under isolated environment:</p><pre>python -m venv .venv</pre><p>Activate virtual env</p><pre>source .venv/bin/activate</pre><p>Install the necessary libraries for Chainlit, OpenAI and LiteralAI</p><pre>pip install chainlit openai literalai</pre><p>The <strong>DineBot</strong> environment is now ready. Lets start utilizing chainlit and build a basic version of the chatbot.</p><h3>Initialize Chatbot project with Chainlit</h3><p>Make sure you are in the same directory i.e dinebot we created above and the virtual env is activated.</p><p>Now run the chainlit init command on the terminal</p><pre>chainlit init</pre><p>This will create the basic files and structure for your chatbot which should look like this</p><pre>Created default config file at dinebot/.chainlit/config.toml<br>Created default translation directory at dinebot/.chainlit/translations<br>Created default translation file at dinebot/.chainlit/translations/gu.json<br>Created default translation file at dinebot/.chainlit/translations/hi.json<br>Created default translation file at dinebot/.chainlit/translations/ml.json<br>Created default translation file at dinebot/.chainlit/translations/en-US.json<br>Created default translation file at dinebot/.chainlit/translations/mr.json<br>Created default translation file at dinebot/.chainlit/translations/ta.json<br>Created default translation file at dinebot/.chainlit/translations/te.json<br>Created default translation file at dinebot/.chainlit/translations/he-IL.json<br>Created default translation file at dinebot/.chainlit/translations/zh-CN.json<br>Created default translation file at dinebot/.chainlit/translations/bn.json<br>Created default translation file at dinebot/.chainlit/translations/kn.json<br>Config file already exists at dinebot/.chainlit/config.toml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*0nJyyN1sv0XrW2N5-hvNDQ.png" /></figure><h3>Set Up the Chatbot</h3><p>Create a new Python file named app.py in the project directory. This file will contain the logic for taking user queries and communicate with LLM for getting an answer to the query.</p><pre>import chainlit as cl<br><br><br>@cl.on_message<br>async def main(message: cl.Message):<br><br>    # Send a response back to the user<br>    user_message = f&quot;Received: {message.content}&quot;<br>    await cl.Message(content=user_message).send()</pre><p>First we are importing the chainlit package and then defining a function that will handle incoming messages from the chatbot UI. Next we are decorating the function with the @cl.on_message decorator to ensure it gets called whenever a user inputs a message.</p><p>The main function will be called every time a user inputs a message in the chatbot UI. You can put your custom logic within the function to process the user’s input, such as analyzing the text, calling an API, or computing a result.</p><p>The <a href="https://docs.chainlit.io/api-reference/message">Message</a> class is responsible for sending a reply back to the user. In this example, we simply send a message containing the user’s input.</p><h3>Run ChatBot</h3><p>Run the following command to start the Chatbot</p><pre>chainlit run app.py --watch --port 8000</pre><p>The --watch flag tells Chainlit to enable auto-reloading, so you don’t need to restart the server every time you make changes to your application. Your chatbot UI should now be accessible at <a href="http://localhost:8000/">http://localhost:8000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1TfjluB3chchVwaL3BQsA.png" /></figure><p>For now, this chatbot will respond whatever you send to it as we didn’t integrate any LLM yet.</p><h3>Train Chatbot to serve as a Restaurant Assistant</h3><p>Let’s make the bot a little more interactive by adding some sample instructions that explain how it should work when users are interacting with the bot.</p><p>Create a new Python file llm.py in the root directory of the project.</p><pre>import chainlit as cl<br>from openai import AsyncOpenAI<br><br>system_message = &quot;&quot;&quot;<br>You are a restuarants Chatbot.<br>An automated service to collect orders for restuarants online.<br>Please process the conversation in this order:<br>- Take the order.<br>- Ask if the order will be delivered or picked.<br>- in case of delivery, ask for the delivery address.<br>- in case of pickup, give the restaurant address for self pick up.<br>- Upon collecting order, first summarize the order for customer, confirm order and address if delivery, from the customer.<br>- Ask for payment whether to be cash on delivery or want to pay via card.<br>- once confirmed, show the final order with prices, delivery or pickup and payment details.<br>- Say good bye with a progressional way.<br><br>Restaurants and Menu:<br><br>## 1. **Din Tai Fung** (Taiwanese)<br>Known for its meticulous and delicious dumplings, Din Tai Fung offers a variety of Taiwanese dishes.<br><br>### Menu:<br><br>#### Appetizers<br>- **Cucumber Salad**: $5.00<br>- **Seaweed &amp; Beancurd in Vinegar Dressing**: $6.00<br><br>#### Rice &amp; Soups<br>- **Fried Rice with Shrimp &amp; Egg**: $11.00<br>- **Hot &amp; Sour Soup**: $6.00<br><br>---<br><br>## 2. **Narisawa** (Japanese - Tokyo)<br>Michelin-starred Narisawa fuses French techniques with traditional Japanese ingredients, focusing on seasonality and environmental sustainability.<br><br>### Menu:<br>#### Seasonal Starters<br>- **Japanese Seasonal Vegetables**: $20.00<br>- **Firefly Squid with Seasonal Ingredients**: $22.00<br><br>#### Main Course<br>- **Charcoal Grilled Wagyu Beef**: $55.00<br>- **Seasonal Fish**: $40.00<br><br>---<br><br>## 3. **Gaggan Anand** (Indian - Bangkok)<br>Gaggan Anand is renowned for his innovative twist on traditional Indian cuisine, often presented in a tasting menu format.<br><br>### Menu:<br>#### Small Bites<br>- **Yoghurt Explosion**: $6.00<br>- **Edible Plastic Spicy Salad**: $8.00<br><br>#### Tandoor<br>- **Tandoori Chicken**: $15.00<br>- **Paneer Tikka**: $12.00<br><br>---<br><br>&quot;&quot;&quot;<br><br>client = AsyncOpenAI()<br><br>messages = [<br>    {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: system_message},<br>]<br><br>async def take_order(message: cl.Message, model=&quot;gpt-4o-mini&quot;, temperature=0.5):<br><br>    messages.append(<br>        {&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: message.content}<br>    )<br><br>    message = cl.Message(content=&quot;&quot;)<br><br>    response = await client.chat.completions.create(<br>        model=model,<br>        messages=messages,<br>        temperature=temperature,<br>        stream=True<br>    )<br><br>    async for part in response:<br>        if token := part.choices[0].delta.content or &quot;&quot;:<br>            await message.stream_token(token)<br><br>    messages.append(<br>        {&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: message.content}<br>    )<br><br>    await message.update()</pre><p>First we are importing chainlit for interacting with chainlit and then importing OpenAI for sending API requests to OpenAI GPT model.</p><p>Next, we are adding a system message for the OpenAI GPT assistant by providing a list of restaurants, its menu and prices for each item in the menu.</p><p>The take_order function will accept whatever message the user has sent. It will append this new user message to the list of messages including system message and any previous messages from the user.</p><p>The reason we are extending the exising list of messages is that, LLM always needs a context for the ongoing chat. So everytime we are receiving a new message from the user, we are appending it to the list of messages and then we are passing that same list of messages to the OpenAI GPT model.<br>Whatever response we get from the GPT model, we add that message content to the chainlit message object so chainlit can update it in the UI.</p><p>Now we just need to call take_order function when a user sends a message from the UI. So lets update our app.py which should look like this now.</p><pre>import chainlit as cl<br>from llm import take_order<br><br><br>@cl.on_chat_start<br>async def on_chat_start():<br>    welcome_message = &#39;Welcome to DineBot. How can I assist you today regarding placing an order?&#39;<br>    msg = cl.Message(content=welcome_message)<br>    await msg.send()<br><br><br>@cl.on_message<br>async def main(message: cl.Message):<br>    await take_order(message)<br><br></pre><p>When the application is loaded, the chatbot will first greet the user by using on_chat_start function and then it will start taking user orders using the main function.</p><p>Before running our Dinebot, lets add a .env file and add the following env vars.</p><pre>CHAINLIT_PORT=8000<br>OPENAI_API_KEY=&quot;sk-proj-****&quot;  # Replace your OpenAI key here</pre><p>Now just run the the chainlit run command and our Dinbot should be ready to start taking orders.</p><pre>chainlit run app.py --watch</pre><p>Visit <strong>Dinebot</strong> at <a href="http://localhost:8000/">http://localhost:8000</a> and try putting some orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iBhdSAVnMDGRPIbOgomZYg.gif" /></figure><h3>Enable Authentication</h3><blockquote>Enabling authentication is required to make chat history persistent</blockquote><p>Chainlit applications are public by default. To enable authentication and make your app private, you need to define a CHAINLIT_AUTH_SECRET environment variable. This is a secret string that is used to sign the authentication tokens. You can change it at any time, but it will log out all users. You can easily generate one using chainlit create-secret add it to the .env file</p><pre>CHAINLIT_AUTH_SECRET=&quot;7U*qm1dwwDXDv@E*S,o34A9VB/dM4DGw*lm&gt;-tVA7TkAa@bWOCW&quot;</pre><p>Now add this snippet to the app.py file for a basic username and password based authentication. If you want to add OAuth, please check <a href="https://docs.chainlit.io/authentication/oauth">here</a>.</p><pre>@cl.password_auth_callback<br>def auth_callback(username: str, password: str):<br>    <br>    # Fetch the user matching username from your database<br>    # and compare the hashed password with the value stored in the database<br>    if (username, password) == (&quot;admin&quot;, &quot;admin&quot;):<br>        return cl.User(<br>            identifier=&quot;admin&quot;, metadata={&quot;role&quot;: &quot;admin&quot;, &quot;provider&quot;: &quot;credentials&quot;}<br>        )<br>    else:<br>        return None</pre><p>Now when you reload your chatbot, it will automatically redirect to the login page. Enter username admin and password admin to login to the chatbot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jVkmyZk6aE3aPOodn1LmGg.png" /></figure><h3>Make Chat History Persistent</h3><p>If you reload the page, you won’t see what you have ordered previously. The reason is, chainlit doesn’t make chat history persistent but it gives you the option to do that using <a href="https://literalai.com/">Literal AI</a>, <a href="https://www.sqlalchemy.org/">SQLAlchemy</a> or <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a>.</p><p>Literal AI can be leveraged as a data persistence solution, allowing you to quickly enable data storage and analysis for your Chainlit app without setting up your own infrastructure.</p><p>To integrate Literal AI, you need to <a href="https://cloud.getliteral.ai/">signup</a> on Literal AI, create a new project and get an API key.</p><p>Add your API key to the .env file.</p><pre>CHAINLIT_PORT=8000<br>OPENAI_API_KEY=&quot;sk-proj-****&quot;<br>CHAINLIT_AUTH_SECRET=&quot;7U*qm1dwwDXDv@E*S,o34A9VB/dM4DGw*lm&gt;-tVA7TkAa@bWOCW&quot;<br>LITERAL_API_KEY=&quot;lsk_****&quot; # Replace your Literal AI key here</pre><p>Hit CTRL + C to stop the running chatbot app and then run</p><pre>chainlit run app.py --watch</pre><p>Now try different chats by ordering different food items from different restaruants and you’ll notice that each time you create a new chat and start interacting with the chatbot, that chat is marked as persistent in the left sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5JK-W1SUrzJzXmp8LojLw.png" /></figure><p>Try logging out and re-login, and you should see all your previous chats.</p><h3>Resume Chat</h3><p>You’ll notice that, you can reload any previous chat from the left sidebar but you cannot start interacting with it by resuming that chat. The reason is, you need to explicitly enable chat resuming in the chainlit.</p><p>Add this function to app.py and we are good with enabling chat resume feature.</p><pre><br>@cl.on_chat_resume<br>async def on_chat_resume():<br>    pass<br></pre><p>On reloading the chatbot, you should see a Resume Chat button at the bottom of each chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yarStzXe8D3CrK8njGqIQ.png" /></figure><p>Clicking on Resume Chat should enable interaction with this chat.</p><p><strong>Source Code on GitHub</strong></p><p><a href="https://github.com/BuildWithLal/ai-powered-chatbots/tree/master/DineBot-AI-Powered-Restaurant-Assistant">ai-powered-chatbots/DineBot-AI-Powered-Restaurant-Assistant at master · BuildWithLal/ai-powered-chatbots</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fk-FcZETtsew%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dk-FcZETtsew&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fk-FcZETtsew%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd07c29ca3f1d03ef5e36420faa8b5d5/href">https://medium.com/media/dd07c29ca3f1d03ef5e36420faa8b5d5/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a><strong> | </strong><a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0?si=6b071022ddc847b9"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7ee6cdf6163" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/build-ai-powered-chatbot-using-chainlint-openai-and-literal-ai-a7ee6cdf6163">Build AI Powered Chatbot using Chainlit, OpenAI and Literal AI</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup GitLab Container Registry — GitLab Managed]]></title>
            <link>https://medium.com/@BuildWithLal/setup-gitlab-container-registry-gitlab-managed-bbda71b3aef4?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbda71b3aef4</guid>
            <category><![CDATA[container-registry]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[gitlab-ci-docker]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 09:01:32 GMT</pubDate>
            <atom:updated>2024-10-24T10:27:50.197Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setup GitLab Container Registry — GitLab Managed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gx79KZo97Z3pdht8KF1BrQ.jpeg" /><figcaption>Source: <a href="https://unsplash.com/@chuttersnap">https://unsplash.com/@chuttersnap</a></figcaption></figure><p>In the series of <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-how-to-easily-set-up-your-own-gitlab-server-9a925be09c59"><strong>Dockerized GitLab</strong></a>, we already have seen how to setup GitLab runner using <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-setting-up-and-connecting-your-gitlab-runner-b810a02e42f2">Shell</a>, <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">Docker</a>, <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-docker-executor-as-a-docker-in-docker-docker-dind-b8557759e557">Docker-in-Docker</a> and <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-build-docker-images-using-google-kaniko-422dc016b78c">Kaniko</a> executors.</p><p>Since we know how to build our dockerized projects using GitLab CI and docker executors. Now is a good time to look into the process of how and where we can push our project’s docker images/builds so later in the deployment stage (CD), we can deploy it to our target servers after we have built it in our GitLab CI.</p><p>With the GitLab container registry, every project can have its own space to store Docker images.</p><h3>Enable Container Registry</h3><p>As we already have our docker-compose.yml file ready for managing GitLab server and Runner containers, we just need to add a couple of additional lines for enabling our GitLab container registry.</p><p>docker-compose.yml can be found in this post</p><p><a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-setting-up-and-connecting-your-gitlab-runner-b810a02e42f2">Dockerized GitLab CI: Setting Up and Connecting Your GitLab Runner</a></p><pre>version: &#39;3.8&#39;<br>services:<br><br>  gitlab-server:<br>    image: &#39;gitlab/gitlab-ce:latest&#39;<br>    container_name: gitlab-server<br>    environment:<br>      GITLAB_ROOT_EMAIL: &quot;admin@buildwithlal.com&quot;<br>      GITLAB_ROOT_PASSWORD: &quot;Abcd@0123456789&quot;<br>      GITLAB_OMNIBUS_CONFIG: |<br>        external_url &#39;http://localhost:8000&#39;<br>        nginx[&#39;listen_port&#39;] = 8000    <br>        <br>        # new changes for enabling container registry<br>        gitlab_rails[&#39;registry_enabled&#39;] = true<br><br>        # docker CLI from inside the pipeline&#39;s job will use this URL to push docker images<br>        registry_external_url &#39;http://localhost:5001&#39;<br>    ports:<br>      - &#39;8000:8000&#39;<br><br>      # expose new port for registry hosting<br>      - &#39;5001:5001&#39;<br>    volumes:<br>      - ./gitlab/config:/etc/gitlab<br>      - ./gitlab/data:/var/opt/gitlab<br><br>  gitlab-runner:<br>    image: gitlab/gitlab-runner:alpine<br>    container_name: gitlab-runner<br>    network_mode: &#39;host&#39;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock</pre><p>Here you can notice that we have just added these 2 new lines and YEAH!, our container registry is ready.</p><pre>gitlab_rails[&#39;registry_enabled&#39;] = true<br>registry_external_url &#39;http://localhost:5001&#39;</pre><p>registry_enabled is self explanatory which enables the registry inside GitLab.</p><p>registry_external_url will make the registry accessible outside GitLab server so we can use docker CLI to login to this registry, push and pull docker images.</p><p>If your containers are already running using docker compose, hit <strong>CTRL+C</strong> to stop running containers and then run this docker compose command to start containers back with new changes applied.</p><pre>docker compose up --build --force-recreate</pre><p>You can check containers health and exposed ports using</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atKICdg_pSYu_u8EHAbX8A.png" /></figure><p>Now you can visit your GitLab dashboard at <a href="http://localhost:8000/">http://localhost:8000</a></p><h3>Setup a new Repository</h3><p>Once you are logged in with your defined user and password from the docker-compose.yml file, Go ahead and create a new repository/project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKlxAfSs967vkj9NP1GdSg.png" /></figure><p>After the repository is created, you should be redirected to the newly created repository and you can see that the <strong>Container Registry</strong> option is now available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rb8j3toBotOunS3IRHZL5Q.png" /></figure><p>For now, we have not pushed any docker images yet so it is empty.</p><p>If you install GitLab by using the Linux package, the container registry may or may not be available by default. So using this way you can enable the container registry. You can also check those helpful docker CLI commands for, how to use the container registry for this project to login and push docker images.</p><h3>Test Container Registry</h3><p>Now to test this registry, we’ll quickly add a <strong>Dockerfile</strong> to our project root directory.</p><p>Dockerfile</p><pre>FROM python:3.10-alpine<br><br>RUN python --version</pre><p>Before we setup our project pipeline, make sure that you have already registered a GitLab runner as a docker executor. IF NOT, please check here</p><p><a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">Dockerized GitLab CI: Register Docker Executor as a GitLab Runner</a></p><p>Once you commit your Dockerfile and you have your Runner ready, lets configure our project pipeline by going to</p><p><strong>Repository → Build → Pipeline Editor → Configure Pipeline</strong></p><p>Add this snippet to your pipeline i.e gitlab-ci.yml file</p><pre>build:<br>    stage: build<br>    image: docker:latest<br>    tags:<br>        - docker<br>    script:<br>        - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login $CI_REGISTRY -u $CI_REGISTRY_USER --password-stdin<br>        - docker build -t &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot; .<br>        - docker push &quot;$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8}&quot;</pre><p>All of these environment variables are predefined variables provided by GitLab. See more details on GitLab CI/CD predefined variables <a href="https://docs.gitlab.com/ee/ci/variables/predefined_variables.html">here</a>.</p><p>The CI_REGISTRY_USER holds a per-job user with read-write access to the container registry. Its password is also automatically created and available in CI_REGISTRY_PASSWORD.</p><p>$CI_REGISTRY is our container registry host URL which is localhost:5001.</p><p>$CI_REGISTRY_IMAGE is the container registry URL for our repository which is localhost:5001/root/build-with-lal</p><p>$CI_REGISTRY_IMAGE:${CI_COMMIT_SHA:0:8} will become localhost:5001/root/build-with-lal:97892e33 which is the full registry image URL for this specific commit.</p><p>0:8 will slice the git commit into first 8 chars only to avoid having long image tags.</p><p>So we are building docker image from our Dockerfile, then we tag that built image which will look like this localhost:5001/root/build-with-lal:97892e33</p><p>And then lastly we push this tagged image to our container registry.</p><p>Once you commit the pipeline changes, the pipeline will run immediately and it should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hN2219VtqpVQIBCrvKISwQ.png" /></figure><p>Now if you go back to your project’s container registry, you should see an image is pushed there</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZwuM8y9pCPwK3jAJnHJaw.png" /></figure><p>Clicking on this repository image i.e build-with-lal will go to the list of all tags you have pushed for this repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-6guc3Q-ixr7NvjuWY05A.png" /></figure><p>Lets copy the image pull URL by clicking on Copy Image Path</p><p>and then run that copied docker pull command on our local terminal</p><pre>docker pull localhost:5001/root/build-with-lal:96e63838</pre><p>You can see that it won’t allow you to pull the docker image from the registry as by default the container registry is private and need authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73DZMPLrc4hIXrHagZq7hA.png" /></figure><p>Now lets try to login to our container registry using docker login</p><pre>docker login --username admin@buildwithlal.com --password Abcd@0123456789 localhost:5001</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOE8FIJ67bfzmw8HtuQ2pQ.png" /></figure><p>It should download that specific tagged image to your local machine.</p><p>So we have enabled container registry, then we tested it by pushing tagged docker images and then we downloaded that image from the container registry into our local maching using docker login and docker pull.</p><h3>Container Registry Storage Backends</h3><p>You can configure the container registry to use various storage backends by configuring a storage driver. By default the GitLab container registry is configured to use the <a href="https://docs.gitlab.com/ee/administration/packages/container_registry.html#use-file-system">file system driver</a> configuration.</p><p>The different supported drivers are:</p><p><strong>Filesystem — </strong>Path on the local file system which is the default storage</p><p><strong>Azure — </strong>Microsoft Azure Blob Storage</p><p><strong>GCS — </strong>Google Cloud Storage</p><p><strong>S3 — </strong>Amazon Simple Storage Service</p><h3>Use file system</h3><p>If you want to store your images on the file system, you can change the storage path for the container registry, follow the steps below.</p><p>The default location where images are stored in Linux package installations is /var/opt/gitlab/gitlab-rails/shared/registry.</p><p>To change it:</p><ol><li>Edit /etc/gitlab/gitlab.rb:</li></ol><pre>gitlab_rails[&#39;registry_path&#39;] = &quot;/path/to/registry/storage&quot;</pre><p>You can add this to docker-compose.yml, the way we’ve added other configurations.</p><p>More details on storage backend can be found here on <a href="https://docs.gitlab.com/ee/administration/packages/container_registry.html#configure-storage-for-the-container-registry">GitLab</a></p><h3>Using 3rd Party Container Registry</h3><p>Using third-party container registries in GitLab was <a href="https://gitlab.com/gitlab-org/gitlab/-/issues/376217">deprecated</a> in GitLab 15.8 and support ended in GitLab 16.0.</p><h3>Registry Authentication</h3><p>Registry doesn’t have a way to authenticate users internally so it relies on GitLab to validate credentials. The connection between Registry and GitLab is TLS encrypted. The key is used by GitLab to sign the tokens while the certificate is used by Registry to validate the signature</p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/gitlab-in-docker/tree/master/09.%20setup-container-registry">gitlab-in-docker/09. setup-container-registry at master · BuildWithLal/gitlab-in-docker</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4Klbfm4CixY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4Klbfm4CixY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4Klbfm4CixY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aae79e996ebb206e1c04402a3d08443/href">https://medium.com/media/2aae79e996ebb206e1c04402a3d08443/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbda71b3aef4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerized GitLab CI: Build Docker Images using Google Kaniko]]></title>
            <link>https://medium.com/@BuildWithLal/dockerized-gitlab-ci-build-docker-images-using-google-kaniko-422dc016b78c?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/422dc016b78c</guid>
            <category><![CDATA[kaniko]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[gitlab-runner]]></category>
            <category><![CDATA[gitlab-ci-docker]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Thu, 19 Sep 2024 09:02:04 GMT</pubDate>
            <atom:updated>2024-10-21T10:42:30.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZfHiULnNIBWJ0Tp6CV0QA.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/a-forklift-is-moving-a-large-container-behind-a-fence-uXc4PvF53fE">https://unsplash.com/photos/a-forklift-is-moving-a-large-container-behind-a-fence-uXc4PvF53fE</a></figcaption></figure><p>In our last 2 posts, we used <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">Docker socket binding from host docker engine</a> and <a href="https://medium.com/p/b8557759e557/edit">Docker-in-Docker service</a> to build docker images inside a GitLab pipeline.</p><p>Former way is giving access to host docker engine through its docker.sock file while later is using docker in privileged mode.</p><p>Job executor using /var/run/docker.sock from host docker engine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdlPlh2T4uVukh7E5jTZUg.png" /></figure><p>Job executor using Docker-in-Dockerservice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3d5UXsmazCY9RgnkjwDH5g.png" /></figure><p>Both ways of getting access to docker engine has some known issues as highlighted by GitLab docs <a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#known-issues-with-docker-socket-binding">here</a> and <a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#known-issues-with-docker-in-docker">here</a>.</p><p>You can notice that in both ways of executing jobs, GitLab runner create child containers either directly on the host docker engine or as child containers inside a service container (dind).</p><p>Kaniko comes into rescue here by building docker images inside a GitLab pipeline without getting access to host Docker either by docker.sock or in privileged mode.</p><h3>What is Kaniko</h3><p>kaniko is a tool to build container images from a Dockerfile, inside a container or Kubernetes cluster.</p><p>kaniko solves two problems with using the Docker-in-Docker build method:</p><p>Docker-in-Docker requires privileged mode to function, which is a significant security concern.<br>Docker-in-Docker generally incurs a performance penalty and can be quite slow.</p><p>To use kaniko with GitLab, a runner with one of the following executors is required:</p><ul><li>Kubernetes</li><li>Docker</li><li>Docker Machine</li></ul><h3>Using Kaniko in GitLab Pipeline Jobs</h3><p>Since we have setup our GitLab Server and Runner using docker compose, make sure your docker-compose.yml looks like this.</p><pre>version: &#39;3.8&#39;<br>services:<br><br>  gitlab-server:<br>    image: &#39;gitlab/gitlab-ce:latest&#39;<br>    container_name: gitlab-server<br>    environment:<br>      GITLAB_ROOT_EMAIL: &quot;admin@buildwithlal.com&quot;<br>      GITLAB_ROOT_PASSWORD: &quot;Abcd@0123456789&quot;<br>      GITLAB_OMNIBUS_CONFIG: |<br>        external_url &#39;http://localhost:8000&#39;<br>        nginx[&#39;listen_port&#39;] = 8000<br>    ports:<br>      - &#39;8000:8000&#39;<br>    volumes:<br>      - ./gitlab/config:/etc/gitlab<br>      - ./gitlab/data:/var/opt/gitlab<br><br>  gitlab-runner:<br>    image: gitlab/gitlab-runner:alpine<br>    container_name: gitlab-runner<br>    network_mode: &#39;host&#39;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock</pre><p>Then run</p><pre>docker compose up</pre><p>Once your GitLab and Runner is ready (healthy) after you confirm it using this command</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBEqgTKA_kI2BYSTV9Y9sw.png" /></figure><p>Go to your GitLab Dashboard here at <a href="http://localhost:8000/">http://localhost:8000</a></p><h3>Register New Runner For Kaniko</h3><p>Create a new <strong>Repository</strong></p><p>Go to <strong>Repository → Settings → CI/CD → Runners</strong></p><p>Click on <strong>New runner </strong>button and fill out the runner details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rizvS7MXu98LlatLGABgA.png" /></figure><p>Click on<strong> Create runner</strong> button and it will redirect you to this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrrGWwDc7cjVgyMxpFtnRA.png" /></figure><p>Login to your GitLab Runner container using this docker compose command</p><pre>docker compose exec -it gitlab-runner /bin/bash</pre><p>And paste the gitlab-runner register …command from the above <strong>Step 1</strong></p><pre>gitlab-runner register \<br>              --url http://localhost:8000  \<br>              --token glrt-Y9BCAyZZyFhrrkezJbC8 \<br>              --executor docker \<br>              --docker-image &quot;gcr.io/kaniko-project/executor:v1.23.2-debug&quot; \<br>              --docker-network-mode &quot;host&quot;</pre><p>Make sure to add --docker-network-mode “host” so job executor container can access the repository in GitLab server using http://localhost:8000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1e8wo-dbY7ZNQY3MgDZ0w.png" /></figure><p>Since Kaniko requires the GitLab runner executor to be one of these:</p><ul><li>Kubernetes</li><li>Docker</li><li>Docker Machine</li></ul><p>We are passing --executor as docker and setting the default docker image to the Kaniko docker image as well</p><p>gcr.io/kaniko-project/executor:v1.23.2-debug</p><p>Once this is processed. Go to <strong>Repository → Settings → CI/CD → Runners</strong></p><p>and you should have a new runner registered for Kaniko</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwwcqoVX4h9Hpq4DdJsAfg.png" /></figure><p>Now we are good to start adding project pipelines.</p><h3>Add Pipeline to .gitlab-ci.yml</h3><p>Before adding our pipeline, lets add a quick Dockerfile to our repository by adding this snippet so we can test building from Dockerfile using Kaniko.</p><p>Dockerfile in repository root directory</p><pre>FROM python:3.10-alpine<br><br>RUN python --version</pre><p>Then Go to <strong>Repository → Build → Pipeline Editor → Configure Pipeline</strong></p><p>and add the following snippet to .gitlab-ci.yml file</p><pre>build with kaniko:<br>  stage: build<br>  tags:<br>    - kaniko<br>  image:<br>    name: gcr.io/kaniko-project/executor:v1.23.2-debug<br>    entrypoint: [&quot;&quot;]<br>  script:<br><br>    # conventional project with Dockerfile inside root dir<br>    - /kaniko/executor --no-push</pre><p>--no-push means that Kaniko will only build the docker image from the Dockerfile and will not push to any container registry which is the default behavior using Kaniko.</p><p>Once you commit the above changes, your pipeline should run immediately and it should look like this after successful execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaAfs2eCHblRr0z_H7DRjA.png" /></figure><h3>docker.sock vs Docker-in-Docker vs Kaniko</h3><p>While the pipeline is running, you can check on the host docker engine that there is only an executor container running. But any container created by the job itself should not be created on the host docker engine which is what we are trying to avoid using Kaniko.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ue8emlGMciYQrakQtayLA.png" /></figure><p>Using <strong>docker socket binding</strong>, we have seen that all of the containers were created on host docker engine including executor container and job’s created containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-HMthqas3nhYRnZKJVxHA.png" /></figure><p>Using<strong> Docker-in-Docker</strong>, we have seen that executor container and service (dind) container were created on host docker engine but any child container created by a job was a child container of the service (container) which required privileged mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jE2shU0DV1m7X_E1qZAYcg.png" /></figure><h3>More on Kaniko CLI</h3><p>If you have your Dockerfile in some nested directory that the project root directory, you can refer to the Dockerfile like thi</p><pre># Dockerfile is in some other directory than root dir<br>- /kaniko/executor --no-push --dockerfile &quot;${CI_PROJECT_DIR}/src/Dockerfile&quot;</pre><p>Or if you Dockerfile is named something else than conventional name i.e Dockerfile</p><pre># Dockerfile is in some other directory than root dir<br>- /kaniko/executor --no-push --dockerfile &quot;${CI_PROJECT_DIR}/mydockerfile&quot;</pre><p>If you want to build your docker image by passing a different context than the root directory</p><pre>- /kaniko/executor<br>      --context &quot;${CI_PROJECT_DIR}/src&quot;<br>      --dockerfile &quot;${CI_PROJECT_DIR}/src/Dockerfile&quot;</pre><p>If you want to push your docker image to some container registry</p><pre>- /kaniko/executor<br>      --context &quot;${CI_PROJECT_DIR}/src&quot;<br>      --dockerfile &quot;${CI_PROJECT_DIR}/src/Dockerfile&quot;<br>      --destination &quot;${CI_REGISTRY_IMAGE}:${CI_COMMIT_TAG}&quot;</pre><h3>Slow uploads when pushing large images</h3><p>When you push large images with kaniko, you might experience long delays.</p><p>This is typically a result of <a href="https://github.com/GoogleContainerTools/kaniko/issues/2751">a performance issue with Kaniko and HTTP/2</a>. The current workaround is to use HTTP/1.1 when pushing with kaniko.</p><p>To use HTTP/1.1, set the GODEBUG environment variable to &quot;http2client=0&quot; in your gitlab-ci.yml file</p><pre>variables:<br>    GODEBUG: &quot;http2client=0&quot;<br></pre><p>More details can be found on Kaniko <a href="https://github.com/GoogleContainerTools/kaniko">here</a></p><p>Now since we can build docker images in our GitLab CI, we need some registry to store our docker images so we can deploy it to some target servers during the deployment stage.</p><p><a href="https://medium.com/@BuildWithLal/setup-gitlab-container-registry-gitlab-managed-bbda71b3aef4">Setup GitLab Container Registry — GitLab Managed</a></p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/gitlab-in-docker/tree/master/08.%20build-docker-images-using-kaniko">gitlab-in-docker/08. build-docker-images-using-kaniko at master · BuildWithLal/gitlab-in-docker</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_xC3ybQUhZg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_xC3ybQUhZg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_xC3ybQUhZg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a43e288dadbe8593c0708956c682f1/href">https://medium.com/media/71a43e288dadbe8593c0708956c682f1/href</a></iframe><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422dc016b78c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerized GitLab CI: Docker Executor as a Docker in Docker (docker:dind)]]></title>
            <link>https://medium.com/@BuildWithLal/dockerized-gitlab-ci-docker-executor-as-a-docker-in-docker-docker-dind-b8557759e557?source=rss-e838a8160361------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8557759e557</guid>
            <category><![CDATA[gitlab-ci-docker]]></category>
            <category><![CDATA[gitlab-runner]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Lal Zada]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 09:01:45 GMT</pubDate>
            <atom:updated>2024-10-13T18:06:07.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_SMe51lMEfeCZgcuMuC0A.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/a-large-ship-in-the-water-2JNNpq4nGls">https://unsplash.com/photos/a-large-ship-in-the-water-2JNNpq4nGls</a></figcaption></figure><p>Continuing the series of <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-how-to-easily-set-up-your-own-gitlab-server-9a925be09c59">Dockerized GitLab</a>, in this post i’ll show you how to register <strong>Docker executor</strong> as a <strong>GitLab runner</strong> with your <strong>GitLab server</strong> for building, testing and deploying your dockerized projects.</p><p>But instead of mounting and using docker socket var/run/docker.sock from our host docker engine, we’ll use <a href="https://hub.docker.com/_/docker"><strong>Docker in Docker</strong></a> aka <strong>dind</strong> for building docker containers inside our project pipelines.</p><p>In our <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">last post</a>, we registered docker executor as a GitLab runner using docker socket /var/run/docker.sock from our host machine’s docker engine and we have seen that all of the containers including job executor container and containers created inside pipeline’s jobs are actually created on our host docker engine. This way of managing docker executor has some potential issues which we discussed as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-HMthqas3nhYRnZKJVxHA.png" /></figure><p>In this post, we are going to register <strong>docker executor</strong> inside our GitLab runner service using another way called <strong>Docker in Docker </strong>aka <strong>dind</strong> for building, testing and deploying our dockerized projects.</p><h3>Docker in Docker</h3><p>Docker in Docker simply means that you are running a docker engine (Daemon) inside a docker container instead of running docker engine on the host machine. Docker in Docker could be useful if you want to manage containers in its own dedicated docker engine, isolated from from the host docker engine and where giving access to the host docker engine could have potential issues.</p><h3>Update Docker Compose File</h3><p>Before we start registering a docker-in-docker executor, we need some minor updates to our docker-compose.yml</p><pre>version: &#39;3.8&#39;<br>services:<br><br>  gitlab-server:<br>    image: &#39;gitlab/gitlab-ce:latest&#39;<br>    container_name: gitlab-server<br>    environment:<br>      GITLAB_ROOT_EMAIL: &quot;admin@buildwithlal.com&quot;<br>      GITLAB_ROOT_PASSWORD: &quot;Abcd@0123456789&quot;<br>      GITLAB_OMNIBUS_CONFIG: |<br>        external_url &#39;http://localhost:8000&#39;<br>        nginx[&#39;listen_port&#39;] = 8000<br>    ports:<br>      - &#39;8000:8000&#39;<br>    volumes:<br>      - ./gitlab/config:/etc/gitlab<br>      - ./gitlab/data:/var/opt/gitlab<br><br>    # new changes for adding gitlab server to custom network<br>    networks:<br>      - gitlab-in-docker<br><br>  gitlab-runner:<br>    image: gitlab/gitlab-runner:alpine<br>    container_name: gitlab-runner<br>    network_mode: &#39;host&#39;<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br><br># new changes for adding custom docker network<br>networks:<br>  gitlab-in-docker:<br>    name: gitlab-in-docker<br>    driver: bridge</pre><p>The update we have made here is that we have put GitLab server container on a custom docker network called gitlab-in-docker with driver bridge. The reason we are doing this is, that docker executor with <strong>docker in docker</strong> doesn’t work with docker host network as docker in docker is using container links and host network cannot be used with container links.</p><blockquote>at least this was what happening to me when trying network host with dind service</blockquote><p>So to clone our project repository inside our pipeline job, job’s container will access our GitLab server using its container name i.e http://gitlab-server:8000 . GitLab server cannot be accessed by using <a href="http://localhost:8000/">http://localhost:8000</a> from within the job’s container because we are not using the host network.</p><p>For this reason, we need to put both GitLab server container and Job executor container on a custom network called gitlab-in-docker so they can access each other by its container names instead of localhost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4VucSisXiKRxJ6Cx1UIZA.png" /></figure><p>Runner needs access to Server container when registering a runner executor. It will get access by localhost as Server is accessible by http://localhost:8000 and Runner container is on the host network so it has access to localhost.</p><p>Job needs access to Server when cloning the repository. It will access it by using Server container name gitlab-server as both job container and Server container are on the same network i.e gitlab-in-docker network.</p><blockquote>Getting bored from neworking? lets jump into the runner registeration part</blockquote><h3>Register Docker in Docker Executor</h3><p>Go to <strong>Repository → Settings → CI/CD → Runners</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtsE5lg_wSrHCy8PVFC5pQ.png" /></figure><p>Click on New project runner button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdvdsHiwN01fZ3198UpQuw.png" /></figure><p>Add Tags so a job could be picked by the runner using its matching executor by tags. Give some description and click on Create runner button. It will redirect you to the below page where you can see the Runner registeration command in <strong>Step 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0ERIEV_GBNdlJ6fGwWLDQ.png" /></figure><p>Copy runner registeration command from <strong>Step 1</strong> and login to your GitLab runner container using below docker compose command.</p><pre>docker compose exec -it gitlab-runner /bin/bash</pre><p>Once logged in to the Runner container, paste the above command from Step 1 inside Runner container and add these additional arguments.</p><p>Make sure to update your --token value from your <strong>Step 1</strong> in the below register command</p><pre>gitlab-runner register  --url http://localhost:8000 \<br>                        --token glrt-qL_FTjkAGqy7SHcYYStx \<br>                        --executor docker \<br>                        --name &quot;Docker in Docker Runner&quot; \<br>                        --docker-image &quot;docker:27.2.0&quot; \<br>                        --docker-privileged \<br>                        --docker-volumes &quot;/certs/client&quot; \<br>                        --docker-network-mode &quot;gitlab-in-docker&quot; \<br>                        --clone-url &quot;http://gitlab-server:8000&quot;</pre><p>We are setting executor to docker the same way we did in our <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-register-docker-executor-as-a-gitlab-runner-71799352c9ac">previous post</a>. Then giving it a meaningful name and setting the default docker image. We are using docker image docker:27.2.0 here so we could have docker CLI available for running docker commands inside our pipeline job.</p><p>To start the build and service (docker in docker) containers, it uses the privileged mode. If you want to use Docker-in-Docker, you must always use privileged = true in your Docker containers.</p><p>We are also mounting /certs/client for the service and job containers, which is needed for the Docker client to use the SSL certificates for connecting in TLS mode.</p><p>And lastly, we are setting the network to gitlab-in-docker which is our custom network and clone URL to http://gitlab-server:8000 which we discussed earlier.</p><p>Once your command is ready, hit Enter and keep hitting Enter while asking for the inputs unless you want to update any value while prompting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnbI-wDG3RokqYwyh_2Yqg.png" /></figure><p>Once this command runs successfully, you should have a success message on your runner page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rZ-BiC9ppbi-hb1muJUbw.png" /></figure><p>Click on the View runners button and you should see all of your runners including your newly registered docker in docker runner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4JhO-aFbW-gAG6QPCbiXg.png" /></figure><p>Now we have our job executor ready. Lets update our .gitlab-ci.yml by going to <strong>Repository → Build → Pipeline Editor → Configure Pipeline</strong></p><p>And then paste the following snippet.</p><pre>build with docker in docker:<br>  stage: build<br>  image: docker:27.2.0<br>  services:<br>    - docker:27.2.0-dind<br>  variables:<br>    DOCKER_HOST: tcp://docker:2376<br>    DOCKER_TLS_CERTDIR: &quot;/certs&quot;<br><br>  tags:<br>    - docker-in-docker<br>  script:<br>    - docker ps<br>    - docker run -d --rm --name nested-container1-in-pipelinejob alpine sleep 20<br>    - docker run -d --rm --name nested-container2-in-pipelinejob alpine sleep 20<br>    - docker ps<br>    - sleep 20</pre><p>services: docker:27.2.0-dind is actually the Docker in Docker provided by Docker officialy. When we define a service for a job, the job will first wait for that service to come up and once that service is ready then the actual job container will start and will process the job’s script part.</p><p>variables will be passed to the job container as env variables for accessing the docker engine from within the job container when running docker CLI commands. DOCKER_TLS_CERTDIR will set the SSL certificates directory while DOCKER_HOST will set the default connectivity to the docker engine via SSL port i.e 2376.</p><p>If you want to connect without TLS, set the variables as below.</p><pre>variables:<br>    DOCKER_HOST: tcp://docker:2375<br>    DOCKER_TLS_CERTDIR: &quot;&quot;</pre><p>Once the docker in docker container/service is ready, the executor will start the job container by pulling the docker:27.2.0 image and then run the script commands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h15a5JQ5S5fbu8GTYleGng.png" /></figure><p>Meanwhile, you can check on your host docker engine that you have 2 new containers. One for the service (dind) and one for the job execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jE2shU0DV1m7X_E1qZAYcg.png" /></figure><p>Once the job reaches the script part and start running the docker containers by running these 2 docker commands</p><pre>- docker run -d --rm --name nested-container1-in-pipelinejob alpine sleep 20<br>- docker run -d --rm --name nested-container2-in-pipelinejob alpine sleep 20</pre><p>This will run 2 new containers inside docker in docker service. You can confirm these 2 new containers by login into the service container</p><pre>docker exec -it 0e7a68f4dfbf sh</pre><p>0e7a68f4dfbf is the docker in docker container ID</p><p>And then run this command to get all containers running inside dind service.</p><pre>docker --tlscacert=/certs/client/ca.pem \<br>       --tlscert=/certs/client/cert.pem \<br>       --tlskey=/certs/client/key.pem \<br>       --tlsverify=1 \<br>       ps</pre><p>Which should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxOul_mp-veHspGwY-I-FQ.png" /></figure><p>So here you can see that we have separated our parent containers i.e gitlab runner, job executor and its child containers from each other by separating from the host docker engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUMwbuLWKtQaCS4mSIcnhg.png" /></figure><h3>Known issues with Docker in Docker</h3><p>Docker-in-Docker is the recommended configuration, but there are some known issues highlighted by GitLab documentation <a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#known-issues-with-docker-in-docker">here</a>.</p><ul><li><strong>The </strong><strong>docker-compose command</strong>: This command is not available in this configuration by default.</li><li><strong>Cache</strong>: Each job runs in a new environment. Because every build gets its own instance of the Docker engine through its services, concurrent jobs do not cause conflicts. However, jobs can be slower because there’s no caching of layers.</li></ul><h3>Alternatives to Docker Executor</h3><p>To build Docker images without enabling privileged mode on the runner or mounting the host docker socket, GitLab has these 2 alternative which you can explore here.</p><ul><li><a href="https://docs.gitlab.com/ee/ci/docker/using_kaniko.html">Kaniko</a></li><li><a href="https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#buildah-example">Buildah</a></li></ul><p>If you want to avoid touching host docker engine completely but still want to build docker images in a CI job, <strong>Kaniko</strong> can help you which i have explained in detail with a demo here in <a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-build-docker-images-using-google-kaniko-422dc016b78c">this post</a>.</p><p><a href="https://medium.com/@BuildWithLal/dockerized-gitlab-ci-build-docker-images-using-google-kaniko-422dc016b78c">Dockerized GitLab CI: Build Docker Images using Google Kaniko</a></p><p><strong>Source Code</strong></p><p><a href="https://github.com/BuildWithLal/gitlab-in-docker/tree/master/05.%20gitlab-runner-with-docker-executor-dind">gitlab-in-docker/05. gitlab-runner-with-docker-executor-dind at master · BuildWithLal/gitlab-in-docker</a></p><p><strong><em>Thank you for making it till the end </em></strong>🎉</p><p><em>If this article helped you, make sure to:</em></p><ul><li><strong>👏 </strong>Clap for the story <strong>(50 claps </strong>🏆<strong>)</strong></li><li>🔔 Follow me: <a href="http://www.youtube.com/@BuildWithLal"><strong>YouTube</strong></a> | <a href="https://www.linkedin.com/in/buildwithlal/"><strong>Linkedin</strong></a> | <a href="https://github.com/BuildWithLal"><strong>GitHub</strong></a> | <a href="https://medium.com/@BuildWithLal"><strong>Medium</strong></a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8tpGRl6QDaU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8tpGRl6QDaU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8tpGRl6QDaU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2fea8e4e311896408d4a43a49d1e470/href">https://medium.com/media/d2fea8e4e311896408d4a43a49d1e470/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8557759e557" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>