https://nitpick92.tistory.com/17

 

[linux] centos nginx Reverse-Proxy 서버 만들기

https://nitpick92.tistory.com/11 [linux] centos7 yum nginx 삭제 및 설치 방법 centos 7 환경에서 nginx 삭제 후 재설치하는 방법에 대해서 알아보려고 합니다. 1. nginx 삭제 # 설치 여부 확인 yum list installed nginx # 삭

nitpick92.tistory.com

지난 시간에는 nginx를 Reverse-Proxy 서버로 사용하는 법을 알아보았습니다.

이어서 하나의 서버에서 여러 도메인을 관리할 수 있는 방법을 알아보겠습니다.

 

nginx multi port

1. nginx conf 파일 수정

# server1
server {
      # 들어오는 port
      listen       8080;
      server_name  localhost;

      error_page   500 502 503 504  /50x.html;
      location = /50x.html {
          root   /usr/share/nginx/html;
      }

      # 실제로 바라볼 port
      location / {
        proxy_pass http://127.0.0.1:9090;
      }
}

# server2
server {
      # 들어오는 port
      listen       8081;
      server_name  localhost;

      error_page   500 502 503 504  /50x.html;
      location = /50x.html {
          root   /usr/share/nginx/html;
      }

      # 실제로 바라볼 port
      location / {
        proxy_pass http://127.0.0.1:9091;
      }
}

2. nginx 서버를 재시작 해줍니다.

sudo systemctl restart nginx

https://nitpick92.tistory.com/11

 

[linux] centos7 yum nginx 삭제 및 설치 방법

centos 7 환경에서 nginx 삭제 후 재설치하는 방법에 대해서 알아보려고 합니다. 1. nginx 삭제 # 설치 여부 확인 yum list installed nginx # 삭제 yum remove {your_pakage_name} 2. nginx 설치 # 기본적으로 nginx를 제공

nitpick92.tistory.com

지난 시간에는 nginx를 설치하는 방법을 알아보았습니다.

 

docker green-blue 무중단 배포를 시도 하던 중 

Reverse-Proxy 서버 역할을 할 수 있는 그 무언가 필요하였습니다.

 

nginx를 Reverse-Proxy 서버로 사용할 수 있도록 세팅하는 방법에 대해 알아보겠습니다.

프록시 서버 이미지

ClientProxy Server에 요청을 하고
Proxy Server는 각 웹서버에 요청 후 받은 응답을
Client에 전달하는 구조 입니다.

1. nginx conf 파일 수정

  • 처음 세팅 시 default.conf를 바라보고 있는데  주석 처리를 해줍니다.
#include /etc/nginx/conf.d/*.conf;
  • server 관련 정보를 입력해줍니다.
server {
      # 들어오는 port
      listen       8080;
      server_name  localhost;

      error_page   500 502 503 504  /50x.html;
      location = /50x.html {
          root   /usr/share/nginx/html;
      }

      # 실제로 바라볼 port
      location / {
        proxy_pass http://127.0.0.1:9090;
      }
}

2. nginx 서버를 재시작 해줍니다.

sudo systemctl restart nginx
8080 포트로 들어오면 실제로는 9090포트를
바라보는 역할을 하도록 세팅을 완료하였습니다.

 

 

.net core 프로젝트JenkinsDocker를 사용하여 
linux 배포서버에 자동배포를 할 수 있도록
CI/CD 구성을 해보려고 합니다.
docker 참고 : https://nitpick92.tistory.com/4
jenkins 참고 : https://nitpick92.tistory.com/14
docker 명령어 참고 : https://nitpick92.tistory.com/5

 

1. 필요한 환경 세팅

  • 로컬 pc (Windows)
    github, docker, visual studio 2022 설치

https://www.docker.com/products/docker-desktop/
Docker Desktop 설치


https://momobob.tistory.com/m/71
WSL2 프로그램 설치

 


  • Jenkins Server (linux CentOS7)
    Jenkins, docker 설치

  • Deploy Server (linux CentOS7)
    docker설치

 


2. 기본동작 확인

자동화 배포 흐름도

  • jenkins 서버에서 github 최신 소스를 pull 받아와 build test를 진행.
  • build test 통과 후 image 제작
  • image -> docker 저장소인 docker hub에 push
  • 프로젝트에 포함돼있는 scripts/deploy.sh를 배포서버에 ssh 전송
  • deploy.sh 실행

3. 프로젝트 준비

docker desktop 동작을 확인해주세요.


 

net core 6.0으로 프로젝트를 생성해 주세요.
Docker 사용을 클릭해 주세요.


 

docker로 프로젝트 실행이 되는지 확인해주세요.

#해당 위치의 dockerfile를 사용하여 image1 생성
docker build -t image1 ./

docker image1 생성 확인

docker image 명령어를 사용하여 image를 생성을 해보세요.

# 생성된 image1 이미지를 사용하여 container1를 생성 후 동작시키는 명령어
docker run -d -p 8080:80 --name container1 image1

docker container 명령어를 사용하여 container를 생성해 보세요.

container 동작을 확인해봅니다.
정상 동작이 완료되면 준비는 끝났습니다.
자신의 Github에 레포지토리 업로드 해주세요.

4. github 접근 토큰 생성

Profile > Settings / Developer settings > Personal access tokens

만들어진 토큰을 안전한 곳에 저장해주세요.


5. github webhook 설정

Repository > Settings > Webhooks

젠킨스 서버 주소/github-webhook/을 연결해주세요.
master branch에 push시 jenkins에 알릴 수 있도록 해주는 역할입니다.

6. docker hub 접근 토큰 생성

Account Settings > Security > New Access Tokens

만들어진 토큰을 안전한 곳에 저장해주세요.


7. 젠킨스 플러그인 설치

https://nitpick92.tistory.com/14

참고하여 설치 후 젠킨스 접속 후 로그인 해주세요.

Jenkins 관리 > Plugin Manager 이동하여 하단 플러그인을 설치해주세요.

  • github integration
  • post build task
  • publish over ssh

8. 젠킨스에 배포 서버 SSH 연결

Dashboard > Jenkins 관리 > Configure System

추후에 deploy.sh파일을 배포서버에 전달해주기 위한 SSH 설정입니다.
ssh or password로 test configuration success 확인 해주시면 됩니다.

 


9. 젠킨스 Credentials Add

Jenkins 관리 > Credentials > System > Global credentials

github에서 만든 접근 토큰을 세팅해줍니다.

docker hub에서 만든 접근 토큰을 세팅해줍니다.

10. 젠킨스 Project 생성

Dashboard > 새로운 item

자신의 github 주소를 연결해주세요.

처음에 세팅한 프로젝트가 업로드된 레포지토리 주소를 적어주세요.
*/master -> master branch에 push를 할때 동작을 하려고 합니다.

Docker Hub Token을 변수에 담아서 사용하기 위한 세팅입니다.

echo $PASSWORD | docker login -u $USERNAME --password-stdin
docker build -t {도커 허브 아이디}/{이미지 네임} ./
docker push {도커 허브 아이디}/{이미지 네임}
docker rmi {도커 허브 아이디}/{이미지 네임}
최신화 된 소스를 대상으로 빌드 테스트 후 Docker Hub에 배포해줍니다.

echo $PASSWORD | docker login -u $USERNAME --password-stdin
sh deploy.sh
Jenkins -> deploy_server1로 프로젝트 scripts폴더에 있는
deploy.sh를 옮기고 실행시켜줍니다.

11. deploy.sh 추가

상단에서 세팅한 프로젝트 scripts폴더 생성 후 deploy.sh를 추가해줍니다.

# 가동중인 testcontainer1 컨테이너 중단 및 삭제
sudo docker ps -a -q --filter "name=testcontainer1" | grep -q . && docker stop testcontainer1 && docker rm testcontainer1 | true

# 기존 이미지 삭제
sudo docker rmi {본인 docker_hub_id}/testimage1

# 도커허브 이미지 pull
sudo docker pull {본인 docker_hub_id}/testimage1

# 도커 run
docker run -d -p 8080:80 --name testcontainer1 {본인 docker_hub_id}/testimage1

# 사용하지 않는 불필요한 이미지 삭제 -> 현재 컨테이너가 물고 있는 이미지는 삭제되지 않습니다.
docker rmi -f $(docker images -f "dangling=true" -q) || true

12. 배포 성공 확인

https://nitpick92.tistory.com/manage/posts/ 

컨테이너 port로 방화벽 오픈 후 배포된 웹 사이트를 확인 해보시면 됩니다.

jenkins 프로젝트 동작 성공
배포된 mvc 프로젝트

 

 

.net core + jenkins + docker를 이용하여 linux 서버에 웹 서비스를 배포하는 방법을 알아보았습니다.

 

궁금한 사항은 댓글 남겨주세요 : )

 

13. 다음에는

현재는 docker container 중지 후 시작하는 사이에는 배포된 웹 페이지에 접속이 불가능한 문제가 있어

무중단 배포에 대해 정리해보려고 합니다.

'Server > 배포 자동화' 카테고리의 다른 글

CentOS7 Jenkins 설치하기  (0) 2023.02.10
# firewalld 설치
sudo yum install firewalld

# firewalld 시작
sudo systemctl start firewalld
sudo systemctl enable firewalld

# port 추가
sudo firewall-cmd --permanent --zone=public --add-port=8080/tcp

#  firewalld  재로드
sudo firewall-cmd --reload

# firewalld 방화벽 리스트 확인
sudo firewall-cmd --list-all

 

외부에서 8080 포트로 접근할 수 있도록 방화벽을 열어주는 작업입니다.

 

배포 자동화에 앞서 Linux CentOS7 환경에
Jenkins를 설치해보고자 합니다.
Jenkins란 배포 자동화를 도와주는 서버입니다.

 

1. 초기 세팅

  • 한국 시간으로 변경
sudo rm /etc/localtime
sudo ln -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime
date
  • java 설치
sudo yum list "java-11-openjdk-devel*"
sudo yum install java-11-openjdk-devel.x86_64
which javac
readlink -f /usr/bin/javac
sudo vim /etc/profile
// 맨 하단에 추가
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-devel.x86_64/bin/javac
PATH=$PATH:$JAVA_HOME/bin
export PATH

source /etc/profile
echo $JAVA_HOME

 

2. Jenkins 설치

# 젠킨스 stable 버전 설치파일 다운로드
sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo

# 젠킨스 설치 key import
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key

# 젠킨스 패키지 설치
sudo yum install jenkins -y

# 젠킨스 설치확인
rpm -qa | grep jenkins

 

3. Jenkins port 변경

  • jenkins port 변경
# jenkins 설정파일 여기 -> 파일권한이 없으면 상황에 맞게 chmod 설정
vi /etc/sysconfig/jenkins

# port 변경

// AS - IS
JENKINS_PORT="8080"

// TO - BE
JENKINS_PORT="9090"
  • jeknins 방화벽 설정
# firewalld 설치
sudo yum install firewalld

# firewalld 시작
sudo systemctl start firewalld
sudo systemctl enable firewalld

# port 추가
sudo firewall-cmd --permanent --zone=public --add-port=9090/tcp

# firewalld 재로드
sudo firewall-cmd --reload

 

  • jenkins 시작
# 젠킨스 시작
sudo systemctl start jenkins.service

# 젠킨스 프로세스 확인
ps -ef | grep jenkins

# 젠킨스 동작 확인
sudo systemctl status jenkins.service

 

4. Jenkins 접속

  • 웹 브라우저 접속(공인ip:port번호) 합니다.
  • pw 확인 합니다.
  • 접속 확인 합니다.
# 패스워드 출력
cat /var/lib/jenkins/secrets/initialAdminPassword

5. Jenkins 세팅

  • install suggested plugins를 클릭하고 계정 생성을 진행합니다.

로그인 화면

  • 해당 플러그인을 설치해줍니다.
1. github integration
2. post build task
3. publish over ssh

Plugin 설치하는 곳

'Server > 배포 자동화' 카테고리의 다른 글

.net core + Jenkins + Docker CI/CD 구성하기  (0) 2023.02.10

 

nft 발급 흐름도

Web3.0은 무엇이고 Nft는 무엇인가에 대해서 조사를 하다가  NFT 토큰을 직접 만들어보기로 하였습니다.

 

필요 환경

1. visual studio code

2. node.js

3. ganache.exe

 

windows 운영체제에서 테스트 진행하였습니다.

 

1. solidity 설치

이더리움 네트워크에서 스마트 컨트랙트 생성을 도와주는 컨트랙트 기반의 고급 프로그래밍 언어입니다.

마켓플레이스에서 solidity, Solidity Contract Flattener, Solidity Extended 설치를 해줍니다.

 

2. truffle 설치

이더리움 기반 solidity 언어를 사용하여 스마트 컨트랙스 개발을 도와주는 프레임워크 입니다.

# truffle 설치
npm install -g truffle

# truffle 세팅
truffle init

# truffle 기본 구조 세팅
truffle unbox pet-shop

 

3. openzeppelin 설치

solidity 기반의 smart contract를 개발할 수 있는 표준 프레임워크 입니다.

# openzeppelin 설치
npm install @openzeppelin/contracts

 

4. nft smart contract 예제 작업

- contracts/TestNftContracts.sol 생성해줍니다.

pragma solidity >=0.4.22 <0.9.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract TestNftContracts is ERC721URIStorage {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    constructor() ERC721("TestNftContracts", "NDP") {}
    //web3.js
    function publishItem(address creator, string memory tokenURI) public returns (uint256){
        _tokenIds.increment(); //1
        
        uint256 newTokenId = _tokenIds.current();
        _mint(creator, newTokenId);
        _setTokenURI(newTokenId, tokenURI);

        return newTokenId;
    }
}

- truffle-config.js 수정해줍니다.

compilers: {
    solc: {
      version: ">=0.4.22 <0.9.0" // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true,        // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: {          // See the solidity docs for advice about optimization and evmVersion
      //  optimizer: {
      //    enabled: false,
      //    runs: 200
      //  },
      //  evmVersion: "byzantium"
      // }
    }
  }

- 수정된 truffle-config.js 컴파일 해줍니다.

truffle compile

- migrations 폴더에 2_contract_migration.js파일을 생성해 줍니다.

var TestNftContracts = artifacts.require("./TestNftContracts.sol");

module.exports = function(deployer) {
  deployer.deploy(TestNftContracts);
};

 

5. 테스트케이스 작업

- test폴더에 DigitalPicture.test.js파일을 생성해 줍니다.

const TestNftContracts =  artifacts.require("TestNftContracts");

contract("TestNftContracts", async function(accounts) {
    // 가나 슈에서 랜덤 주소
    const [owner] = accounts;
    
    // 무조건 한번 실행
    beforeEach(async function(){
        this.token = await TestNftContracts.new();
    });
     
    // image 주소는 각자 환경에 맞춰서 넣어주시면 됩니다.
    it("publish item", async function(){
        const tokenId = await this.token.publishItem(owner, "https://dev.image/aa.png");
        console.log(tokenId);
    });
});

 

6. ganache 설치 및 세팅

가상의 이더리움 네트워크를 생성하여 스마트 컨트랙트를 실행할 수 있도록 해주는 프로그램입니다.

 

- ganache 설치

https://trufflesuite.com/ganache/

 

Ganache - Truffle Suite

Features VISUAL MNEMONIC & ACCOUNT INFO Quickly see the current status of all accounts, including their addresses, private keys, transactions and balances.

trufflesuite.com

- truffle-config.js 를 수정해줍니다.

networks: {
    development: {
     host: "127.0.0.1",     // Localhost (default: none)
     port: 7545,            // Standard Ethereum port (default: none)
     network_id: "5777",       // Any network (default: none)
    },

 

ganache 세팅

 

7. 테스트 케이스 실행

truffle test ./test/DigitalPicture.test.js

 

결과값 출력

 

8. 오류 발생 처리

truffle 세팅 시 해당 오류가 발생할 수 있습니다.

 

이 시스템에서 스크립트를 실행할 수 없으므로 ~ps... 오류 발생시

https://nitpick92.tistory.com/12

 

이 시스템에서 스크립트를 실행할 수 없으므로 ~... 오류 발생시

visual studo code에 truffle 세팅 중 해당 오류가 발생하였습니다. 해당 오류를 해결하는 법을 알아보겠습니다. 1. windows powershell을 관리자로 실행 2. 현재 권한상태 확인 # 현재 권한상태 확인 get-Executio

nitpick92.tistory.com

9. 앞으로

만들어진 nft 토큰을 블록체인 네트워크에서 가져오는 작업을 해보려고 합니다.

nft-api/nft-api: NFT API that returns resolved metadata and has all information about all NFT collections, users, transactions. Cross-Chain NFT API. (github.com)

 

 

visual studo code에 truffle 세팅 중 해당 오류가 발생하였습니다.

해당 오류를 해결하는 법을 알아보겠습니다.

 

1. windows powershell을 관리자로 실행

2. 현재 권한상태 확인

# 현재 권한상태 확인
get-ExecutionPolicy

3. 권한상태 변경

# 권한 상태를 변경
Set-ExecutionPolicy RemoteSigned

이러면 깔끔하게 실행이 됩니다.

 

 

centos 7 환경에서 nginx 삭제 후 재설치하는 방법에 대해서 알아보려고 합니다.

 

1. nginx 삭제

# 설치 여부 확인
yum list installed nginx

# 삭제
yum remove {your_pakage_name}

2. nginx 설치

# 기본적으로 nginx를 제공하지 않기 떄문에 저장소 설정필요
vi /etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

# nginx 설치
yum install nginx -y

3. port 변경

# 방화벽 포트 열기
firewall-cmd --permanent --zone=public --add-port=9090/tcp

# 재부팅
firewall-cmd --reload

# 포트 확인
firewall-cmd --list-ports

# nginx 포트 설정
vi /etc/nginx/conf.d/default.conf
listen       9090;

# systemctl enable nginx
# systemctl start nginx

4. 동작 확인

github 소스를 참고하던중 해당 오류가 발생했습니다.

# gci -Recurse {해당 파일 path} | Unblock-File
gci -Recurse "D:\WinformExample" | Unblock-File

 

CentOS 서버에 Redis를 설치해보려고 합니다.

Redis 설치 후 방화벽을 열어 외부에서 접근할 수 있도록 하겠습니다.

Port는 60379로 변경하여 사용하도록 하겠습니다.

 

1. 사전 작업

# Memory  설정
sudo sysctl vm.overcommit_memory=1
sudo echo "vm.overcommit_memory=1" >> /etc/sysctl.conf

# Memory 적용 확인
sudo sysctl -a | grep vm.overcommit

# TCP Backlog 설정
sudo sysctl -w net.core.somaxconn=1024
sudo echo "net.core.somaxconn=1024" >> /etc/sysctl.conf 

# TCP Backlog 적용 확인
$ sudo sysctl -a | grep somaxconn

# 한국 시간 변경
sudo rm /etc/localtime
sudo ln -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime
date

2. Redis 설치

# EPEL Repository install
sudo yum install epel-release

# yum update
sudo yum update

# redis install
sudo yum install redis

# redis 실행
sudo systemctl start redis

# redis 중지
sudo systemctl stop redis

# redis 자동 시작
sudo systemctl enable redis

# redis 설치 확인
redis-cli ping

3. Redis port 변경

 

# redis config 파일 접근
sudo vi /etc/redis/redis.conf

# bind 변경
bind 0.0.0.0

# port 변경
port 60379

# 비밀번호 설정
requirepass 1234

4. 방화벽 열기

# firewalld 설치
sudo yum install firewalld

# firewalld 시작
sudo systemctl start firewalld
sudo systemctl enable firewalld

# port 추가
sudo firewall-cmd --permanent --zone=public --add-port=60379/tcp

# firewalld 재로드
sudo firewall-cmd --reload

5. redis-cli 접근 확인

# redis-cli -h [외부 ip] -p [port] -a [password]
redis-cli -h [외부 ip] -p 60379 -a 1234

 

 

 

 

 

+ Recent posts