1. github에 cdn_vtx_nginx Repository 생성

  • github의 Repository 생성

  • VS Code의 코드를 통해 github에 등록하기 위해 기초 적업 진행 → 향후 add, commit, push를 통해 쉽게 github에 동기화 가능
    $ echo "# cdn_vtx_nginx" >> README.md
    $ git init
    $ git add README.md
    $ git commit -m "first commit"
    $ git branch -M main
    $ git remote add origin https://github.com/HippoMans/cdn_vtx_nginx.git
    $ git push -u origin main

  • Jenkins에서 자동으로 Repository를 일기 위해서 Webhook 설정 →Payload URL의 설정은 Jenkins IP:12080

2. 이미지를 push, pull할 Docker Private Repository에 cdn_vtx_nginx Repository 생성

  • Docker Private Repository는 Harbor Private Repository를 사용


3. Jenkins Pipeline 생성


4. ArgoCD에 cdn_vtx_nginx APP 생성


5. Jenkinsfile 생성 내용

  • Jenkins Pipeline 내용 → Github Repository에 Jenkisfile으로 업로드

    $ vi Jenkinsfile
    podTemplate(label: 'docker-build',
      containers: [
        containerTemplate(
          name: 'git',
          image: 'alpine/git',
          command: 'cat',
          ttyEnabled: true
        ),
        containerTemplate(
          name: 'docker',
          image: 'docker',
          command: 'cat',
          ttyEnabled: true
        ),
      ],
      volumes: [
        hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock'),
      ]
    ) {
        node('docker-build') {
            def dockerHubCred = "private-docker-registry-ID"
            def appImage
    
            stage('Start'){
                slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Start -> URL : ${env.BUILD_URL}")
            }
    
            stage('Checkout'){
                container('git'){
                    try{
                        checkout scm
                        slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Checkout Success.")
                    }catch(e){
                        slackSend(Channel: '#hippo_cicd', color: '#ff0000', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Checkout Failed.")
                        throw e
                    }
                }
            }
    
            stage('Build'){
                try{
                    container('docker'){
                        script {
                            appImage = docker.build("cdn_vtx_nginx/nginx")
                        }
                        slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Build Success.")
                    }
                }catch(e){
                    slackSend(Channel: '#hippo_cicd', color: '#ff0000', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Build Failed.")
                    throw e
                }
            }
    
            stage('Test'){
                container('docker'){
                    try {
                        script {
                            appImage.inside {
                                sh 'nginx -t'
                            }
                            slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Test Success.")
                        }
                    }catch(e){
                        slackSend(Channel: '#hippo_cicd', color: '#ff0000', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Test Failed.")
                        throw e
                    }
                }
            }
    
            stage('Push'){
                container('docker'){
                    try {
                        script {
                            docker.withRegistry('https://www.hippo.com', dockerHubCred){
                            appImage.push("${env.BUILD_NUMBER}")
                            appImage.push("latest")
                            }
                        slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Push Success.")
                        }   
                    }catch(e){
                        slackSend(Channel: '#hippo_cicd', color: '#ff0000', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Push Failed.")
                        throw e
                    }
                }
            }
            stage('Complete') {
                sh "echo 'Checkout & Build & Test & Push is finished'"
                slackSend(Channel: '#hippo_cicd', color: '#000dff', message: "${env.JOB_NAME}[#${env.BUILD_NUMBER}] Pipeline Complete.")
            }
        }   
    }

6. Dockerfile 생성 내용

  • 생성된 Dockerfile 내용 → Github Repository에 Dockerfile으로 업로드

    $ vi Dockerfile
    FROM centos:7
    
    RUN yum update -y && \
        yum install -y GeoIP \
                 wget \
                 nginx-module-geoip \
                 perl-ExtUtils-Embed \
                 geoip-devel \
                 gperftools-devel \
                 gcc \
                 g++ \
                 cpp \
                 gcc-c++ \
                 openssl \
                 openssl-devel \
                 gd \
                 gd-devel \
                 libxml2-devel \
                 bzip2-devel \
                 curl-devel \
                 libicu-devel \
                 libmcrypt \
                 libmcrypt-devel \
                 openldap \
                 openldap-devel \
                 git \
                 libxslt-devel
    
    WORKDIR /root
    
    RUN wget http://nginx.org/download/nginx-1.20.1.tar.gz && \
        tar -C /root/ -xzvf nginx-1.20.1.tar.gz
    
    RUN git clone git://github.com/vozlt/nginx-module-vts.git
    
    WORKDIR /root/nginx-1.20.1
    
    RUN  ./configure --prefix=/usr/share/nginx \
                 --sbin-path=/usr/sbin/nginx \
                 --modules-path=/usr/lib64/nginx/modules \
                 --conf-path=/etc/nginx/nginx.conf \
                 --error-log-path=/var/log/nginx/error.log \
                 --http-log-path=/var/log/nginx/access.log \
                 --http-client-body-temp-path=/var/lib/nginx/tmp/client_body \
                 --http-proxy-temp-path=/var/lib/nginx/tmp/proxy \
                 --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi \
                 --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi \
                 --http-scgi-temp-path=/var/lib/nginx/tmp/scgi \
                 --pid-path=/run/nginx.pid \
                 --lock-path=/run/lock/subsys/nginx \
                 --user=nginx \
                 --group=nginx \
                 --with-compat \
                 --with-debug \
                 --with-file-aio \
                 --with-ipv6 \
                 --with-google_perftools_module \
                 --with-http_addition_module \
                 --with-http_auth_request_module \
                 --with-http_dav_module \
                 --with-http_degradation_module \
                 --with-http_flv_module \
                 --with-http_gunzip_module \
                 --with-http_gzip_static_module \
                 --with-http_image_filter_module=dynamic \
                 --with-http_mp4_module \
                 --with-http_perl_module=dynamic \
                 --with-http_random_index_module \
                 --with-http_realip_module \
                 --with-http_secure_link_module \
                 --with-http_image_filter_module \
                 --with-http_slice_module \
                 --with-http_ssl_module \
                 --with-http_stub_status_module \
                 --with-http_sub_module \
                 --with-http_v2_module \
                 --with-http_xslt_module=dynamic \
                 --with-mail=dynamic \
                 --with-mail_ssl_module \
                 --with-pcre \
                 --with-pcre-jit \
                 --with-stream=dynamic \
                 --with-stream_ssl_module \
                 --with-stream_ssl_preread_module \
                 --with-threads \
                 --with-http_xslt_module=dynamic \
                 --with-http_image_filter_module=dynamic \
                 --with-http_geoip_module \
                 --with-http_perl_module=dynamic \
                 --with-mail=dynamic \
                 --add-module=/root/nginx-module-vts/ \
                 --with-stream=dynamic
    
    RUN make && make install
    
    WORKDIR /root
    RUN useradd -r nginx
    RUN mkdir -p /var/lib/nginx/tmp/client_body
    RUN mkdir -p /etc/nginx/sites-available
    RUN mkdir -p /var/cache/nginx/temp/
    
    ADD http://20.10.195.172/nginx_config/nginx_cache_default.conf /etc/nginx/nginx.conf  # nginx 설정 파일 (제공 X)
    ADD http://20.10.195.172/nginx_config/nginx_sites_cache.conf /etc/nginx/sites-available/cache.conf   # vhost 파일 (제공 X)
    ADD http://20.10.195.172/nginx_config/cache_params /etc/nginx/cache_params  # cache_params 내용 (제공 X)
    
    VOLUME ["/cache1/", "/cache1/"]
    VOLUME ["/cache2/", "/cache2/"]
    
    EXPOSE 80
    EXPOSE 443
    
    CMD ["nginx", "-g", "daemon off;"]

7. 쿠버네티스 배포 yaml 파일

  • 쿠버네티스에 nginx 배포할 yaml 파일 내용 → Github Repository에 업로드되면 ArgoCD에서 해당 내용 배포

    $ vi cdn_vtx_nginx.yml
    apiVersion: v1
    kind: Namespace
    metadata:
      name: cdn-vtx-nginx
    ---
    
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: cdn-vtx-nginx-deployment
      namespace: cdn-vtx-nginx
    spec:
      selector:
        matchLabels:
          nginx: cdn-vtx-nginx
      replicas: 1
      strategy:
        type: Recreate
      template:
        metadata:
          labels:
            nginx: cdn-vtx-nginx
        spec:
          containers:
          - name: container
            image: www.hippo.com/cdn_vtx_nginx/nginx:latest    ## harbor private registry의 Repository 위치
            ports:
            - containerPort: 80
            volumeMounts:
             - name: cache1
               mountPath: /cache1
             - name: cache2
               mountPath: /cache2
          nodeSelector:
            kubernetes.io/hostname: [worker node의 hostname]
          volumes:
          - name: cache1
            hostPath:
              path: /cache1
              type: Directory
          - name: cache2
            hostPath:
              path: /cache2
              type: Directory
          imagePullSecrets:
          - name: harbor-secret
    ---
    
    apiVersion: v1
    kind: Service
    metadata:
      name: cdn-vtx-nginx-loadbalancer
      namespace: cdn-vtx-nginx
    spec:
      selector:
        nginx: cdn-vtx-nginx
      ports:
        - name: http
          port: 80
          targetPort: 80
          protocol: TCP
      type: NodePort
    ---
    
    apiVersion: v1
    kind: Service
    metadata:
      name: cdn-vtx-nginx-service
      namespace: cdn-vtx-nginx
    spec:
      selector:
        nginx: cdn-vtx-nginx
      type: ClusterIP
      ports:
        - name: http
          port: 80
          targetPort: 80
          protocol: TCP
    ---
    
    apiVersion: v1
    data:
      .dockerconfigjson: eyJhdXRocyI6eyJodHRwczovL3Rlc3RoaXBwby5teXNrY2RuLmNvbSI6eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiJIYXJib3JBZG1pbjEyMzQiLCJlbWFpbCI6InRlQGdtYWlsLmNvbSIsImF1dGgiOiJZV1J0YVc0NlNHRnlZbTl5UVdSdGFXNHhNak0wIn19fQ==
    kind: Secret
    metadata:
      name: harbor-secret
      namespace: cdn-vtx-nginx
    type: kubernetes.io/dockerconfigjson

8. 최초 Jenkins Build는 직접 해야함 → 이후 Webhook을 통해 자동 갱신

  • Jenkins CI Build 실행

  • SLACK을 통해 Jeknis 작업 내용 전달 → 성공은 파랑색, 실패는 빨강색

9. Docker Private Repository(Harbor) 이미지 생성 확인

  • Jenkins의 Build 번호가 Tag로 표시
  • latest는 가장 최근에 Push한 파일이 들어있음

10. ArgoCD 배포 확인(쿠버네티스에서 배포되는 형태)

  • 생성된 내용은 간략한 그림으로 제공

11. 쿠버네티스의 최종 배포 확인과 테스트 서비스 유무 확인

  • cdn-vtx-nginx 네임스페이스에 배포 확인

  • gitlab에서 container registry를 사용
  • IP를 사용했기에 SSL 적용 불가
  • SSL을 사용하지 않고 container registry를 사용하에 불안정
  • 향후 gitlab에 SSL 인증서를 사용하여 적용하는 방법 테스트 필요

container registry 활성화를 위하여 gitlab.rb 설정파일 변경

  • container registry 사용하기 위해서는 아래 내용 설정 필요

    $ vi /etc/gitlab/gitlab.rb
    #### ...중략...
    gitlab_rails['gitlab_default_projects_features_container_registry'] = true
    
    ####... 중략...
    ####################################################################
    ## Container Registry settings
    ##! Docs: https://docs.gitlab.com/ee/administration/container_registry.html
    ####################################################################
    
    registry_external_url 'https://IP:8001'
  • gitlab 설정을 변경하였다면 재설정과 재시작
    $ gitlab-ctl reconfigure
  • gitlab 페이지에 container resitry 생성 확인

flask를 활용하여 version 1을 확인할 수 있는 docker 이미지 생성

1. docker 이미지에 사용할 파일 내용 소개

  • version1의 flask 내용 → server.py

    $ vi server.py
    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello, world!\n'
    
    @app.route('/version')
    def version():
        return 'version 1\n'
    
    if __name__ == '__main__':
        app.run('0.0.0.0', port=9000, debug=True)
  • python 서버를 실행하기 위해 필요한 flask 패키지 다운 → pip을 통해 flask 패키지를 docker 이미지 내에 다운
    $ vi requirements.txt
    Flask==1.1.2
  • docker 이미지를 생성하기 위한 Dockerfile 파일 내용

    $ vi Dockerfile
    FROM python:3.7-alpine
    
    WORKDIR /usr/src/app
    
    COPY . .
    
    RUN pip install --no-cache-dir -r requirements.txt
    EXPOSE 9000
    
    ENTRYPOINT ["python3"]
    
    CMD ["server.py"]

2. docker 이미지 생성 → hippo_flask:v1으로 생성

  • 이미지 이름 : hippo_flask
  • 이미지 tag : v1
    $ docker build -t hippo_flask:v1 ./
    Sending build context to Docker daemon  4.096kB
    Step 1/7 : FROM python:3.7-alpine
    3.7-alpine: Pulling from library/python
    59bf1c3509f3: Already exists
    8786870f2876: Already exists
    [...생략...]
    Step 6/7 : ENTRYPOINT ["python3"]
     ---> Running in 1cc769d232d6
    Removing intermediate container 1cc769d232d6
     ---> 07e5df487c7e
    Step 7/7 : CMD ["server.py"]
     ---> Running in 0383d99cef58
    Removing intermediate container 0383d99cef58
     ---> 64d54ca5156c
    Successfully built 64d54ca5156c
    Successfully tagged hippo_flask:v1
  • 생성한 docker 이미지 확인
    $ docker images hippo_flask
    REPOSITORY    TAG       IMAGE ID       CREATED              SIZE
    hippo_flask      v1        64d54ca5156c   About a minute ago   51.7MB

3. hippo_flask:v1 docker 이미지를 통해 컨테이너 생성과 확인

  • 컨테이너 생성
    $ docker run --name version1 -d -p 9000:9000 hippo_flask:v1
    3d75997676b1f71d80eb72070ac3dbba9695ead6810b8d2a6cefcc1bad83b939
  • 생성된 컨테이너 확인
    $ docker ps | grep version1
    3d75997676b1   hippo_flask:v1         "python3 server.py"      14 seconds ago   Up 13 seconds   0.0.0.0:9000->9000/tcp, :::9000->9000/tcp   version1


생성된 컨테이너 통신 테스트

1. 생성된 컨테이너에 트래픽 전송하여 정상적으로 통신 되는지 curl 트래픽 전송 테스트

  • curl 명령어를 통해 통신 확인
    $ curl localhost:9000/version
    version 1

2. 생성된 컨테이너에 for문을 활용하여 연속적으로 트래픽 전송

  • 배포하는 과정에서 변화를 알기 위해 curl를 for 통해 무한 사용
    $ for (( ; ; )) do curl localhost:9000/version; sleep 1; done
    version 1
    version 1
    version 1
    version 1
    version 1
    version 1
    version 1
    ^C

3. 생성한 컨테이너 종료

# 종료할 hippo_flask:v1 컨테이너 확인
$ docker ps | grep hippo_flask
3d75997676b1   hippo_flask:v1         "python3 server.py"      2 minutes ago   Up 2 minutes   0.0.0.0:9000->9000/tcp, :::9000->9000/tcp   version1

# 해당 컨테이너 종료
$ docker rm -f 3d75997676b1


# 컨테이너가 출력되지 않았으므로 정상적으로 삭제된 것 확인
$ docker ps | grep hippo_flask



gitlab private container registry에 이미지 올리기

1. gitlab private container registry 로그인

  • gitlab에 container registry에 로그인 작업 필요 → [서버 IP]:8001로 로그인 시도

  • docker login 명령어 입력 후 Username과 Password를 입력하면 로그인됨

    $ docker login [서버 IP]:8001
    Username: root
    Password:
    WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
    Configure a credential helper to remove this warning. See
    https://docs.docker.com/engine/reference/commandline/login/#credentials-store
    
    Login Succeeded
  • ※ 참고 → docker repository에 http로 접근하면 오류 발생
    $ docker login [서버 IP]:8001
    Username: root
    Password:
    Error response from daemon: Get "https://서버 IP:8001/v2/": http: server gave HTTP response to HTTPS client
  • 해결 방법 → 접근 시도하는 서버의 docker 설정 변경(insecure-registries 내용 부분 추가)

    $ vi /etc/docker/daemon.json
    {
      "insecure-registries": ["서버 IP:8001"],
      "exec-opts": ["native.cgroupdriver=systemd"],
      "log-driver": "json-file",
      "log-opts": {
        "max-size": "100m"
      },
      "storage-driver": "overlay2",
      "storage-opts": [
        "overlay2.override_kernel_check=true"
      ]
    }
    
    # daemon.json를 적용하기 위해 docker 재실행
    $ systemctl retart docker

2. gitlab private container registry에 등록할 image 생성

  • [서버 IP]:8001 주소를 가진 gitlab에 /root/test 경로로 이미지 생성
    $ docker build -t [서버 IP]:8001/root/test .
    Sending build context to Docker daemon  4.096kB
    Step 1/7 : FROM python:3.7-alpine
     ---> a1034fd13493
    Step 2/7 : WORKDIR /usr/src/app
     ---> Using cache
     ---> 5ab0544a8338
    Step 3/7 : COPY . .
     ---> Using cache
     ---> e1867730ab46
    Step 4/7 : RUN pip install --no-cache-dir -r requirements.txt
     ---> Using cache
     ---> 6bb03c2fca00
    Step 5/7 : EXPOSE 9000
     ---> Using cache
     ---> fbbd26c4f799
    Step 6/7 : ENTRYPOINT ["python3"]
     ---> Using cache
     ---> 07e5df487c7e
    Step 7/7 : CMD ["server.py"]
     ---> Using cache
     ---> 64d54ca5156c
    Successfully built 64d54ca5156c
    Successfully tagged 180.70.134.124:8001/root/test:latest
  • 생성 이미지 이름 확인
    $ docker images | grep -i "[서버 IP]:8001"
    [서버 IP]:8001/root/test                    latest         64d54ca5156c   33 minutes ago   51.7MB

3. gitlab private container registry에 이미지 push

  • gitlab private container registry에 push 후http://[서버 IP]:8001/root/test/container_registry 접속해서 로그인하면 업로드된 화면을 확인 가능
    $ docker push hippo7788/hippo_flask:v1
    The push refers to repository [docker.io/hippo7788/hippo_flask]
    fca7f999dd38: Pushed
    07a451b20a57: Pushed
    20093ec82cc4: Pushed
    4df147e7bcb6: Pushed
    880c61470517: Mounted from library/python
    45d4d0cf56eb: Mounted from library/python
    619b8ea44798: Mounted from library/python
    a2f23be74558: Mounted from library/python
    e2eb06d8af82: Mounted from library/python
    v1: digest: sha256:d8a803d8b0d05dd42d0563c4151d370b5f9a50808611a62bdaeffd22332bcdce size: 2204
  • gitlab private container registry에 업로드 확인
  • docker hub에 업로그한 이미지 다운받아서 확인 → 이전에 사용한 컨테이너와 이미지는 삭제

    # 컨테이너 삭제 -> docker ps로 확인 가능
    $ docker rm -f 5fefc9b6e072
    5fefc9b6e072
    
    # 이미지 삭제 -> docker images로 확인 가능
    $ docker rmi -f hippo_flask
    Untagged: hippo_flask:v1
    
    # 이미지 삭제 -> docker images로 확인 가능
    $ docker rmi -f 8dc659fae720
    Untagged: hippo7788/hippo_flask:v1
    Untagged: hippo7788/hippo_flask@sha256:d8a803d8b0d05dd42d0563c4151d370b5f9a50808611a62bdaeffd22332bcdce
    Deleted: sha256:8dc659fae720e2989a727e504fc712a6433500a55ef8bba911fcd802dde65f74
    Deleted: sha256:aa987e77dfe966494d486e3a7d49bcda9e46b3620471911ba59eecd4ca9c7736
    Deleted: sha256:a4c264e5cc48f12f09b0a57670de350bc9ccd4aec7210411a21261938c4bee51
    Deleted: sha256:ea20f857309d14f754678a3de6d98037473656f0654c4392ffb30f3d61d1716c
    Deleted: sha256:9c5b47ae8a6edd9e6d8549dde338997b5cd0e32f97d1b973c36301520afb2590
    Deleted: sha256:be4379647236972f9cee3f1508c8821e619703060c2bb79058f746b36c8a31c3
    Deleted: sha256:54ebb48e2f85190b5ac7a315e667becad4520727455c8e061861d89609dc3d31
    Deleted: sha256:0458e8557286e301e0e59bc2555979a3ebbd0212012b54c25670d7375714b697
    Deleted: sha256:bf7be436ba34ac4068d4c1f1eaf07d1d46ffc6457bc73dc2fd9a1dda39d0cd2b
    Deleted: sha256:38f374f0f73da0d857c17772f78c586cebfc3354f5fe8419a0bdb14a7a47b235
    Deleted: sha256:a944a01d620ff5361172590ce45ea48dc38b8c564a154a99f876ae0bc0e01827



Docker Hub에 올린 이미지를 다운 후 컨테이너 실행 → hippo7788/hippo_flask:v1

1. Docker Hub에 있는 hippo7788/hippo_flask:v1 이미지를 통해 컨테이너 생성

  • 이미지 다운 후 컨테이너 확인

    $ docker run --name version1 -d -p 9000:9000 hippo7788/hippo_flask:v1
    Unable to find image 'hippo7788/hippo_flask:v1' locally
    v1: Pulling from hippo7788/hippo_flask
    a0d0a0d46f8b: Already exists
    c11246b421be: Already exists
    c5f7759615a9: Already exists
    6dc4dde3f226: Already exists
    f2db6ae633c1: Already exists
    9c864080a3a4: Pull complete
    615272ced259: Pull complete
    82808996193e: Pull complete
    71f74dbb2c6d: Pull complete
    Digest: sha256:d8a803d8b0d05dd42d0563c4151d370b5f9a50808611a62bdaeffd22332bcdce
    Status: Downloaded newer image for hippo7788/hippo_flask:v1
    f478fb738e1f7cf8f10a787581910cc8cf5e966bf6c9bc2d328199c996947be1
    
    # 생성된 컨테이너 확인
    $ docker ps | grep version1
    f478fb738e1f        hippo7788/hippo_flask:v1   "python3 server.py"      42 seconds ago      Up 41 seconds       0.0.0.0:9000->9000/tcp   version1
    
    # 생성된 이미지 확인
    $ docker images hippo7788/hippo_flask
    REPOSITORY              TAG                 IMAGE ID            CREATED             SIZE
    hippo7788/hippo_flask   v1                  8dc659fae720        2 hours ago         54MB

2. 생성된 컨테이너에 트래픽 전송하여 정상적으로 통신 되는지 curl 트래픽 전송 테스트

  • 다운받은 이미지의 컨테이너가 실행되는 지 테스트
    $ curl localhost:9000/version
    version 1

  • gitlab 공식 사이트의 설치 가이드 제공 URL → https://about.gitlab.com/install/#centos-7?version=ce
  • gitlab을 docker container registry로 사용 가능
  • 쿠버네티스 CI/CD 파이프라인으로 활용 가능
  • 무료 버전인 ce(Community Edition)을 찾아서 설치해야 라이선스 없이 설치 가능
  • 공식사이트의 설치가이드를 따라 설치하면 ee(Enterprise Edition)의 가이드를 보여주기 때문에 ee버전을 설치 → 주의 필요

gitlab을 설치하기 전의 사전작업 (메일서버 설치)

  • gitlab에서 사용자 가입 인증이나 관리자에게 Alerts이나 기타 이유로 메일을 보내야 하므로 메일 서버를 설치
    $ yum install postfix -y
    $ systemctl enable --now postfix
    $ systemctl status postfix


gitlab 패키지 설치하기

1. 패키지 저장소 등록

  • curl를 이용하여 gitlab package repository를 등록
    $ curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash

2. 패키지 설치

  • yum을 이용하여 등록된 패키지를 설치
  • EXTERNAL_URL은 지금 설치한 gitlab 웹사이트에 접속할 URL을 입력
  • 보통 도메인이 있으면 도메인명을 입력하지만 도메인이 없는 경우 일단 그냥 IP번호를 작성해도 됨
  • Port를 다른 포트로 사용한다면 port번호도 :으로 구분하여 작성 → port는 8001로 가정
  • yum install -y gitlab-ce 설치
    # EXTERNAL_URL="자신의 도메인이나 접속가능한 IP:접속할 Port번호" yum install -y gitlab-ce
    $ EXTERNAL_URL="[서버 IP]:8001 또는 도메인" yum install -y gitlab-ce

3. 설치한 gitlab 실행

  • 설치에 별 문제가 없는 경우는 설치가 완료
  • 도메인 또는 [서버 IP]:8001을 웹브라우저에 입력하면 gitlab 로그인 화면 출력되면 설치에 반은 성공


4. 설치한 gitlab에 로그인

  • 최초 접속 시 로그인 아이디는 root
  • 최초 접속시 root 비밀번호 갱신 → qwer1234
    $ gitlab-rails console -e production
    irb(main):005:0> user = User.where(id: 1).first
    => #<User id:1 @root>
    irb(main):006:0> user.password='qwer1234'
    => "qwer1234"
    irb(main):007:0> user.password_confirmation='qwer1234'
    => "qwer1234"
    irb(main):008:0> user.save
    => true
  • root 계정 로그인 성공

gitlab 설정하기

  • gitlab의 설정은 설치된 폴더에서 gitlab.rb을 변경
  • 보통 설치 위치는 /etc/gitlab/gitlab.rb → gitlab 많은 설정이 해당 파일에서 적용 가능
    $ vi /etc/gitlab/gitlab.rb

1. 업로드 파일 용량 변경

  • 한번에 업로드해야 할 파일의 용량이 큰 경우 사이즈 조정 필요 → 업로드 파일 용량을 1G로 제한
  • 앞에 주석(#)을 제거해야 반영됨
    $ vi /etc/gitlab/gitlab.rb
    ## ...중략...
    nginx['enable'] = true
    nginx['client_max_body_size'] = '1G'

2. 레파지토리 저장 디렉토리 위치 변경

  • 기본은 지정된 레파지토리 저장위치가 있으나 드라이브를 별도로 추가하여 운영하는 경우는 다른 드라이브로 저장 위치를 변경해야함

  • git_data_dirs 함수 아래에 원하는 저장 디렉토리를 지정

  • /dev/sdb1와 mount된 /data 디렉토리 아래에 gitlab_data에 저장(/data/gitlab_data)

  • /data/gitlab_data/ 디렉토리가 없다면 해당 디렉토리 생성 필요

    $ mkdir /data/gitlab_data
    
    # 레파지토리 저장 디렉토리 위치 변경
    $ vi /etc/gitlab/gitlab.rb
    ## ...중략...
    git_data_dirs({
      "default" => {
        "path" => "/data/gitlab_data"
       }
    })

3. 도메인 생성 및 SSL 적용

  • IP를 사용할 경우 SSL 사용 X

  • SSL을 사용하는 경우 도메인 필요

  • /etc/gitlab/ssl 디렉토리로 crt, key 파일 복사 필요

    $ vi /etc/gitlab/gitlab.rb
    
    external_url 'https:/도메인'
    nginx['redirect_http_to_https'] = true
    nginx['redirect_http_to_https_port'] = 80
    
    nginx['ssl_certificate'] = "/etc/gitlab/ssl/도메인.crt"
    nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/도메인.key"
    
    # 도메인 생성 및 SSL 설정 적용
    $ gitlab-ctl reconfigure



gitlab 터미널 명령어

  • 대표적인 gitlab의 터미널 명령어

1. gitlab 재설정 후 재시작

  • gitlab 설정을 변경하였다면 재설정과 재시작
    $ gitlab-ctl reconfigure

2. gitlab 시작

  • gitlab 시작
    $ gitlab-ctl start

3. gitlab 종료

  • gitlab 종료
    $ gitlab-ctl stop

4. gilab 재시작

  • gitlab 재시작
    $ gitlab-ctl restart


gitlab 삭제

  • gitlab를 삭제해야 할 경우는 아래의 명령어로 삭제
  • 남아있는 폴더나 파일이 있는경우 수동으로 삭제 필요

1. gitlab 명령어 삭제

  • gitlab 삭제
    $ gitlab-ctl uninstall
    $ gitlab-ctl cleanse
    $ gitlab-ctl remove-accounts
    $ dpkg -P gitlab-ce || sudo yum -y remove gitlab-ce

2. 수동삭제 → rm -rf 명령어로 해당 디렉토리 삭제

  • gitlab 삭제에 필요한 디렉토리 목록
    - /opt/gitlab
    - /var/opt/gitlab
    - /etc/gitlab
    - /var/log/gitlab

+ Recent posts