Skip to content

Instantly share code, notes, and snippets.

@Curookie
Last active September 14, 2023 15:13
Show Gist options
  • Save Curookie/cb3c384b7e96f24d6ee843623a1a88ed to your computer and use it in GitHub Desktop.
Save Curookie/cb3c384b7e96f24d6ee843623a1a88ed to your computer and use it in GitHub Desktop.
AWS 서버 구축하기

세팅

오른쪽 위 생성 지역이 서울인지 체크
EC2 인스턴스 >> 태그 부분에서 name : 팀이름 >> 용량부분에서 8GB -> 30GB >> 보안그룹 (팀이름-SG)과 HTTP 80, HTTPS 443, Custom 3000 (nodejs) 준비
실행하고 새 키 받기 해서 .pem 받아두기
연결 > EC2 인스턴스 연결 > 연결 로 ec2-user 접속

탄력적 IP - 끌때마다 아이피 바뀌는거 방지

계정 및 패스워드 세팅

  1. 매번 pem 키 위치를 적어주는건 귀찮으므로 pem 키페어 파일을 ~/.ssh/로 복사한다. (여기 놔두면 자동으로 pem 키 파일을 읽는다.)
    $ cp [pem 키 위치] ~/.ssh/
    마지막으로 pem 키의 권한을 변경해준다.
    $ chmod 600 ~/.ssh/{pem 키 이름}

  2. root password 설정
    [ec2-user@ip-172-31-7-114 ~]$ sudo passwd root

  3. password 기반의 로그인을 활성화하기
    [ec2-user@ip-172-31-7-114 ~]$ sudo vi /etc/ssh/sshd_config

Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

위의 no를 yes로 변경한 후 저장한다.

  1. root 계정으로 로그인
    [ec2-user@ip-172-31-7-114 ~]$ su - root

  2. 다른 사용자 계정 추가
    [root@ip-172-31-7-114 ~]$ adduser jmkim

  3. 새로 생성한 사용자 계정의 비밀번호 변경
    [root@ip-172-31-7-114 ~]$ sudo passwd jmkim

  4. 새로 생성한 사용자 계정에 root 권한을 사용할 수 있도록 설정
    [root@ip-172-31-7-114 ~]$ sudo visudo

root ALL=(ALL) ALL 아래에
jmkim ALL=(ALL) ALL 을 추가해 준다.

아니면 wheel 그룹권한
sudo gpasswd -a junhyeong wheel

  1. 같은 key pair로 로그인 할 수 있도록 새로 생성한 사용자 계정으로 ec2-user 의 것을 복사

이부분에 대한 자세한 내용은 SSH KEY 를 참고한다. (https://opentutorials.org/module/432/3742)
ubuntu 에서.ssh 폴더를 생성해 주어야한다.

[root@ip-172-31-7-114 ~]$ sudo cp -pr /home/ec2-user/.ssh/ /home/jmkim/.ssh/

  1. 복사한 key pair의 소유자를 jmkim으로 변경 (-R : 하위 폴더까지 모두 소유권을 바꿔줌)
    [root@ip-172-31-7-114 ~]$ sudo chown -R jmkim:jmkim /home/jmkim/.ssh

  2. sshd 서비스 재시작
    [root@ip-172-31-7-114 ~]$ sudo service sshd restart

ubuntu
[root@ip-172-31-7-114 ~]$ sudo service ssh restart

Visual Studio Code

윈도우에서 AWS Visual Studio Code로 연결할 때
~.pem 파일 오른쪽 버튼 속성 > 보안 > 고급 > 아래 상속안함 클릭하고 모두 삭제 > 새로 추가한다음 자기 User 이름만 넣고 읽기 실행만 체크하면 접속 가능
그래도 안되면 git bash 같은거로 chmod 600 인걸 -> chmod 400 으로 바꾸면 됨.

EC2 기본 세팅 (AMI)

// 현재 시간 (Timezone 확인)
sudo date
// localtime 삭제
sudo rm -rf /etc/localtime
// timezone Aisa/Seoul 로 변경
sudo ln -s /usr/share/zoneinfo/Asia/Seoul /etc/localtime
// 변경된 시간 (Timezone) 확인 후 마무리
sudo date

sudo yum update -y
sudo yum install gcc gcc-c++

sudo yum install -y git  
git config --global user.name Curookie  
git config --global user.email [email protected]  
$ ssh-keygen -t rsa -C "[email protected]"      
$ cat {저장된 경로/id_rsa.pub}  

//node npm 설치
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node

도커로 설치할거면 설치 ㄴㄴ sudo yum install -y nginx  //이거 안되면 아래꺼로
도커로 설치할거면 설치 ㄴㄴ sudo amazon-linux-extras install -y nginx1  
제거하는 방법 sudo service nginx stop  
sudo chkconfig nginx off  
sudo yum remove nginx  
sudo yum install -y docker
sudo curl -L https://github.com/docker/compose/releases/download/{최신버전 찾아서 }/docker-compose-`uname -s`-`uname -m` | sudo tee /usr/local/bin/docker-compose > /dev/null  
sudo chmod +x /usr/local/bin/docker-compose  
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose  
이전 버전 제거 하는 방법 sudo rm /usr/local/bin/docker-compose
 
sudo service docker start #Docker 서비스 실행   
sudo chkconfig docker on #부팅시 자동 실행  

Docker 명령

sudo docker-compose up -d yml 파일로 여러 컨테이너를 백그라운드로 실행 
sudo docker container ls 컨테이너 목록 확인
// 컨테이너 일괄 시작/정지/재시작
$ docker-compose start
$ docker-compose stop
$ docker-compose restart  
// 여러 컨테이너의 상태 확인
$ docker-compose ps
 docker-compose down
--rmi all	모든 이미지를 삭제
--rmi local	커스컴 태그가 없는 이미지만 삭제
-v, --volumes	Compose 정의 파일의 데이터 볼륨을 삭제
$ docker-compose run server_a /bin/bash 다음의 명령은 docker-compose up 명령을 사용하여 시작한 server_a 라는 이름의 컨테이너에서 /bin/bash를 실행하는 예이다.

docker-compose logs 로그
docker exec -it mongodb-container bash 



.env 라는 파일에
MONGO_ROOT_USER=devroot
MONGO_ROOT_PASSWORD=devroot
MONGOEXPRESS_LOGIN=dev
MONGOEXPRESS_PASSWORD=dev

mkdir mongo-storage
chown -R 999:999 mongo-storage


두 컨테이너의 docker network ip 정보를 알아내기 위해 다음의 명령어를 이용하여 어떤 docker network에 연결되었는지를 알아낸다.

$ docker network ls
본인의 경우 express-tutorials_default 라는 docker network에 묶여있었다. 따로 설정하지 않을 경우 {프로젝트 폴더명_default}으로 설정되는 듯 하다.

$ docker inspect {docker_network_name} 
위의 명령어를 통해 해당 network에 묶인 컨테이너 중 mongo의 ip주소를 알아낸다.  

React

node -v or node –version
npm -v or npm –version
npm install -g create-react-app
npx create-react-app my-app
npm start

관리

free -m
find . -empty -type d -delete -print 현재 폴더에 빈 디렉토리 모두 제거
sudo netstat -ntlp 포트 

스왑 메모리 세팅  
swapon -s  
스왑 메모리 지정여부 체크  
fallocate -l 2GB /swapfile  

ll / 명령어로 파일이 생성되었는지 확인합니다.  
chmod 600 /swapfile  파일을 시스템에서만 접근이 가능하게 위 명령어로 퍼미션을 설정합니다.   
mkswap /swapfile 명령어로 스왑 포맷 형태로 변환하면 위와 같은 결과를 볼 수 있습니다.  
swapon /swapfile 스왑 파일을 시스템에 등록합니다.  

vi /etc/fstab  

/swapfile swap swap defaults 0 0  


top 명령어  
SHIFT+P : CPU 사용률이 많은 프로세스 순서대로 정렬  
SHIFT+M : MEMORY 사용률이 많은 프로세스 순서대로 정렬  
SHIFT+T : 실행 시간이 오래된 프로세스 순서대로 정렬  
SHIFT+B : 주요값을 밝게 표시  
 

MongoDB

mongo 접속  
mongo -u root 루트로 접속
show dbs 디비목록  
db 현재디비  
show collections 컬랙션 보여주기  
show users 사용자 정보
db.person.insert({"nickname":"freekim", "email":"[email protected]"}) 입력  
db.person.find() 검색  
db.createUser({user:"mysns_user", pwd: passwordPrompt(), roles:["readWrite", {role:"read",db:"myblog"}]}) 계정
apt-get update
apt-get install vim

use mongodb_tutorial 디비생성
db.createCollection(name, [options])


security:
   authorization : enabled

db.createUser( { user: "mongo",
... pwd: "password123",
... roles: ["root"] }
... )

// 사용자 정보 가져오기
// ____________________________________________________________________________
db.getUser("USER")
// DB에 존재하는 전체 사용자 정보 가져오기
db.getUsers()

// 인증(로그인...)
// ____________________________________________________________________________
db.auth("USER", "PASSWD")

// 비밀번호 변경
// ____________________________________________________________________________
db.changeUserPassword("USER", "NEW_PASSWD")

// 사용자 정보 갱신
// ____________________________________________________________________________
// 비밀번호 갱신 = db.changeUserPasswd()
db.updateUser("USER", {pwd: "NEW_PASSWD"})
// customData 갱신
db.updateUser("USER", {customData: {name:"백충덕", age:36}})
// roles 갱신
db.updateUser("USER", {roles:["read"]})
// 여러 데이터 갱신
db.updateUser("USER", {pwd: "NEW_PASSWD", roles: ["read"]})

// 권한 변경
// ____________________________________________________________________________
// 권한 추가
db.grantRolesToUser("USER", ["NEW_ROLE1", "NEW_ROLE2"])
// 권한 제거
db.revokeRolesFromUser("USER", ["DEL_ROLE1", "DEL_ROLE2"])

// 사용자 삭제
// ____________________________________________________________________________
db.dropUser("USER")

 
$eq : (equals) 주어진 값과 일치하는 값
$gt : (greater than) 주어진 값보다 큰 값
$gte : (greather than or equals) 주어진 값보다 크거나 같은 값
$lt : (less than) 주어진 값보다 작은 값
$lte : (less than or equals) 주어진 값보다 작거나 같은 값
$ne : (not equal) 주어진 값과 일치하지 않는 값
$in : 주어진 배열 안에 속하는 값
$nin : 주어빈 배열 안에 속하지 않는 값

$or
$and
$not
$nor

docker restart $(docker ps -q) 모든 도커 

Nginx 웹서버

$ sudo yum install nginx // Amazon Linux 1 환경
$ sudo amazon-linux-extras install nginx1 // Amazon Linux 2 환경

sudo systemctl start nginx 실행하는 

새로운 버전을 배포할 때마다 이뤄지도록 해야 한다.
$ yarn install
$ yarn run build

$ sudo vi /etc/nginx/nginx.conf

...

include /etc/nginx/conf.d/*.conf;
(✨ 코드 추가) include /etc/nginx/sites-enabled/*.conf;

# server {
#    listen       80 default_server;
#    listen       [::]:80 default_server;
#    server_name  _;
#    root         /usr/share/nginx/html;
    # Load configuration files for the default server block.
#    include /etc/nginx/default.d/*.conf;
#    location / {
#    }
#    error_page 404 /404.html;
#        location = /40x.html {
#    }
#    error_page 500 502 503 504 /50x.html;
#        location = /50x.html {
#    }
# }

일반적인 방식은 sites-available 디렉토리에 필요한 파일들을 작성한 후 이들과 연결되는 symbolic link(symlink)를 sites-enabled에 추가하는 것이다. 때문에 /etc/nginx 내부에 두 디렉토리를 모두 생성해 준다. 그리고 sites-available 내에 원하는 이름으로 설정 파일을 생성해 열도록 한다.

$ sudo mkdir /etc/nginx/sites-available
$ sudo mkdir /etc/nginx/sites-enabled
$ sudo vi /etc/nginx/sites-available/#######.conf
지금은 도메인 등록도 되어있지 않고, HTTPS를 위한 준비도 되어있지 않으므로, HTTP에 해당하는 port 80에 대해서 아주 기본 설정만 포함한다.

server {
  listen 80;
  location / {
    root /home/ec2-user/#######/#######/build;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
  }
}
location 뒤의 /는 directive라고 하는 부분인데, IP 주소나 도메인의 뒷부분인 URI에 대응된다. /만 쓰면 ‘/’로 시작하는 모든 URI에 해당한다는 것으로 현재 설정은 이 인스턴스의 IP 주소로 port 80을 통해 들어오는 모든 URL을 연결시켜주는 것이다.
root 행에는 아까 Git을 통해 가져온 프로젝트 내부의 build 디렉토리 경로를 입력한다.

$ sudo ln -s /etc/nginx/sites-available/#######.conf /etc/nginx/sites-enabled/#######.conf
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
위와 같은 내용이 출력되면 설정의 문법이 정상적이라는 것이다.

$ sudo systemctl start nginx
만약, 500 Internal Server Error가 발생한다면, build까지의 경로로 접근할 때 거치는 디렉토리들에 대해 외부에서의 실행 권한이 없어서 발생하는 문제일 가능성이 높으므로, 홈 디렉토리인 /home/ec2-user의 권한을 others의 실행 권한을 포함한 711로 설정한다.

$ chmod 711 /home/ec2-user

# 시스템 컨트롤에서 nginx 자동시작 설정
systemctl enable nginx.service

# 시스템 컨트롤에서 nginx 자동시작 해제
systemctl enable nginx.service

# nginx 상태 보기
systemctl status nginx.service

# nginx 재시작
systemctl restart nginx.service

중지
sudo systemctl stop nginx
sudo service nginx stop 

Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
중간에 disabled가 나타나면 ec2가 재시작해도 nginx는 시작되지 않습니다.



유료 SSL 설정법

server {
  listen 80;
  listen [::]:80;

  server_name *.crayonboys.com;

  location / {
    return 301 https://$host$request_uri;
  }
}

server {
        listen 443;
        listen [::]:443;
        server_name *.crayonboys.com;

        ssl     on;
        ssl_certificate /etc/ssl/Wildcard.crayonboys.com_pem.pem;
        ssl_certificate_key /etc/ssl/KeyFile_Wildcard.crayonboys.com_pem.key;

        location / {
                root /home/nft/OpenseaMint/nft/build;
                index index.html index.htm;
                try_files $uri $uri/ /index.html;
        }
        location /api {
                proxy_pass http://localhost:3003;
        }
}

무료 SSL

sudo yum install -y epel-release
sudo yum install -y certbot-nginx

certbot --nginx -d my.domain.com

sudo certbot --nginx -d jannabiclub.com -d www.jannabiclub.com -d api.jannabiclub.com 

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Enter email address (used for urgent renewal and security notices)
 (Enter 'c' to cancel): [이메일 주소]
 
이용 약관에 동의합니다.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

EFF의 소식을 이메일로 받을지 선택합니다.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y

conf 파일 수정
server {
        listen 80;
        listen [::]:80;

        server_name 도메인;

        location / {
                return 301 https://$host$request_uri;
        }
}

server {
        listen 443;
        listen [::]:443;
        server_name 도메인;

        ssl     on;
        ssl_certificate /etc/letsencrypt/live/도메인/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/도메인/privkey.pem;

        location / {
        		root /opt;
                index   index.html;
                try_files $uri $uri/ /index.html;
        }
        location /api { // api 경로 proxy pass 처리
                proxy_pass http://localhost:3001;
        }
}

도메인 자동갱신 설정(crontab)
crontab -e
1 1 1 * * certbot renew --quiet --renew-hook "service nginx restart"

sudo systemctl restart crond

sudo fuser -k 80/tcp

nginx를 재시작하면 잘 돌아간다.


502 BAD Gateway
에러 메시지 확인 sudo cat /var/log/nginx/error.log

server {
  listen 80;
  listen [::]:80;
  server_name crayonbets.com www.crayonbets.com;

#  location / {
#    root /home/nft/OpenseaMint/nft/build;
#    index index.html index.htm;
#    try_files $uri $uri/ /index.html;
#  }

  location / {
    return 301 https://$host$request_uri;
  }
}

server {
  listen 443;
  listen [::]:443; # managed by Certbot
  server_name crayonbets.com www.crayonbets.com;

  ssl on;
  ssl_certificate /etc/letsencrypt/live/crayonbets.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/crayonbets.com/privkey.pem;
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

  location / {
    root /home/nft/OpenseaMint/nft/build;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
  }
  
  location /api {
    proxy_pass http://localhost:3003;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass_request_headers      on;
    client_max_body_size 100M;
    rewrite ^/api/?(.*) /$1 break;
  }
}


pm2 24시간 자동실행 서버

sudo npm install pm2 -g

-- start
pm2 start app.js --name my-app
pm2 start server.json << json 설정파일이 있을 경우 이걸로 start 함

-- 설정 저장
pm2-startup install
pm2 save

-- 등록된 pm2 설정 지우기
pm2-startup uninstall

-- save 했던 환경 설정파일로 다시 시작
pm2 resurrect

-- 리부트
pm2 reboot

-- app 재시작
pm2 restart <<id>> or <<app name>>

-- 클러스터 모드를 사용할 때는 reload를 사용하면 다운 타임 없이 서버 재가동 됨
pm2 reload <<id>> or <<app name>>

-- app 정지
pm2 stop <<id>> or <<app name>>

-- app 목록에서 제거
pm2 del <<id>> or <<app name>>

-- 서비스 리스트 조회
pm2 ls or pm2 list

-- 모니터링
pm2 monit

# pm2 클러스터 모드
$ pm2 start node/app.js -i 10

# pm2 scale in/out
$ pm2 scale <name> <숫자>

마지막으로, 클러스터 모드를 사용할 때는 start 대신에 reload를 사용하여야 한다. restart의 경우에는 모든 프로세스를 종료하고 재시작하는 것이나, reload를 사용한다면 다운타임 없이 서버를 재기동할 수 있기 때문이다.

# pm2 클러스터 모드 재시작
$ pm2 reload <id|name>

다음의 명령어를 통해서 PM2의 설정 파일을 생성할 수 있다.

# pm2 설정파일 생성하기
$ pm2 ecosystem

pm2 start index.js --watch --ignore-watch="log/*"

watch 옵션을 주면 애플리케이션에 변동사항이 있을 시에 자동으로 재시작합니다.
코드를 수정한 후 깃에서 pull을 해 와도 재시작할 필요가 없다는 이야기죠.

4. 시스템 시작시 현재 프로세스 자동 시작시키기

pm2 startup [사용OS]
사용 OS 는 생략시 자동으로 pm2가 찾는다

[PM2] You have to run this command as root. Execute the following command:
      sudo su -c "env PATH=$PATH:/usr/local/bin pm2 startup linux -u jinyongwha --hp /home/jinyongwha"
      
5. 위와 같은 메세지가 나오게되는데 아랫줄의 명령어를 그대로 커맨드창에 입력
sudo su -c "env PATH=$PATH:/usr/local/bin pm2 startup linux -u jinyongwha --hp /home/jinyongwha"

is not in the sudoers file.  This incident will be reported.

위와같은 메세지가 나오면 해당계정은 sudo 로 루트권한을 가질수 없는상태이다
/etc/sudoers 파일에 아래와같이 계정을 추가시켜준다

5. 위와 같은 메세지가 나오게되는데 아랫줄의 명령어를 그대로 커맨드창에 입력


pm2 프로세스 저장하기
pm2 save

만약 지우고 싶다면 pm2 unstartup을 해주면 됩니다.

재시작 후 
$ systemctl status pm2-ubuntu

mongoDB 설치

vi /etc/yum.repos.d/mongodb-org-5.0.repo

[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc


sudo yum install -y mongodb-org

vi /etc/mongod.conf 

net:
  port: 27017
  bindIp: 0.0.0.0

security: 
  authorization: enabled 
  
service mongod restart   

backup.sh 작성
#!/bin/sh
mongodump -h 127.0.0.1 -u root -p xxxx -o /home/ec2-user/dbbackup/dump_$(date +%y%m%d-%H%M)
외부 몽고디비를 백업

$ mongodump -h 호스트:포트 -d 디비명 -u 사용자계정 -p 비밀번호 -o 백업폴더


crontab 에 등록
$ crontab -e
입력 후 반복작업 등록
sudo crontab -e

# 매시간 정각에 backup.sh 수행
0 * * * * /home/ec2-user/dbbackup/backup.sh


등록된 계획 확인
$ crontab -l
# 매시간 정각에 backup.sh 수행
0 * * * * /home/ec2-user/dbbackup/backup.sh
$ 


복구
$ mongorestore -h 127.0.0.1 ~/dump/
connected to: 127.0.0.1
....
외부 몽고디비 서버로 복원

$ mongorestore -h 호스트:포트 -d 디비명 -u 사용자계정 -p 비밀번호 백업폴더
ex) mongorestore -h ds239911.mlab.com:39911 -d anony -u user01 -p xxxx anony

RabbitMQ 큐 시스템

sudo yum -y update

sudo amazon-linux-extras install epel -y

<!-- 
sudo yum install erlang

sudo yum remove erlang* -->

cd ~ && wget https://packages.erlang-solutions.com/erlang/rpm/centos/7/x86_64/esl-erlang_23.3.1-1~centos~7_amd64.rpm

sudo yum -y install esl-erlang*.rpm

sudo vim /etc/yum.repos.d/rabbitmq_erlang.repo

# In /etc/yum.repos.d/rabbitmq_erlang.repo
[rabbitmq_erlang]
name=rabbitmq_erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
       https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

[rabbitmq_erlang-source]
name=rabbitmq_erlang-source
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
       https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

sudo yum install yum-plugin-versionlock

sudo yum versionlock gcc-*

sudo yum install -y socat

sudo yum install logrotate

http://www.rabbitmq.com/releases/rabbitmq-server 버전 확인   

cd ~ && wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.9.11/rabbitmq-server-3.9.11-1.el7.noarch.rpm
sudo rpm -Uvh rabbitmq-server-3.9.11-1.el7.noarch.rpm

$ sudo systemctl start rabbitmq-server.service
$ sudo systemctl enable rabbitmq-server.service
$ sudo rabbitmqctl status

sudo rabbitmq-plugins enable rabbitmq_management


During activation, the plugin creates a default administrator account named guest. Delete this account to avoid security issues:

$ sudo rabbitmqctl delete_user guest

Add a new account for accessing the web UI. In the following commands, replace admin with your desired account name:

$ sudo rabbitmqctl add_user admin

$ sudo rabbitmqctl set_user_tags admin administrator

Grant appropriate permissions to the admin account:

$ sudo rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"

Add a new/fresh user, say user test and password test:
rabbitmqctl add_user guest1 guest1

Give administrative access to the new user:
rabbitmqctl set_user_tags guest1 administrator

Set permission to newly created user:
rabbitmqctl set_permissions -p / guest1 ".*" ".*" ".*"

To enable access to the RabbitMQ management web UI and other common features, update the firewall rules to allow inbound TCP traffic on ports 4369, 25672, 5671, 5672, 15672, 61613, 61614, 1883, and 8883.
<!-- 
$ sudo firewall-cmd --zone=public --permanent --add-port=4369/tcp --add-port=25672/tcp --add-port=5671-5672/tcp --add-port=15672/tcp  --add-port=61613-61614/tcp --add-port=1883/tcp --add-port=8883/tcp
Reload the current firewall session to apply the change:

$ sudo firewall-cmd --reload

인바운드 규칙으로 대체
 -->

sudo rabbitmq-plugins list

sudo rabbitmqctl purge_queue NFTQueue
큐 

rabbitmqctl list_connections
rabbitmqctl list_consumers
rabbitmqctl close_connection <connectionpid> <explanation>

sudo rabbitmqctl list_connections pid port state user vhost recv_cnt send_cnt send_pend name \
 | grep -vP 'Listing|pid' \
 | awk '{print "sudo rabbitmqctl close_connection \"" $1 "\" \"manually closing idle connection\"" }' > delete.sh\
 
 backup.sh 파일의 첫 행에 #!/bin/bash 를 추가해준다.
 
chmod 700 backup.sh
./backup.sh


 600개 죽이기
 
타임아웃 세팅

sudo rabbitmqctl eval 'application:set_env(rabbit, heartbeat, 1800).'

IP 우회 TOR 설치

sudo yum install tor  
9050 포트 열기   
sudo chmod -R 777 /run/tor  
sudo systemctl start tor  

CURL 명령어

대문자 -O는 파일을 원래 파일 이름으로 저장합니다.
curl -O https://cdn.jsdelivr.net/npm/vue/dist/vue.js

Proxy 서버는 -x 옵션으로 지정 가능합니다.
curl -X POST\
-H Content-Type:application/json\
-H Authorization: Bearer abcdbdg\
-d @data.json\

-X, --request Specify request command to use
-H, --header HTTP Header에 에 추가. 위 예제에서는 Content-Type:application/json 과 Authorization: Bearer abcdbdg을 추가함
-d, --data HTTP POST data
--data-ascii HTTP POST ASCII data
--data-binary HTTP POST binary data

$ curl -v - A "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.3 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36" http://example.com

다중 파일들 내용변경

find . -name '*.php' -exec sed -i -e 's/www.fubar.com/www.fubar.ftw.com/g' {} ;

파일 용량 관리

  1. 디스크 별 용량 확인 df -h
  2. 특정 디렉토리 용량 확인 du -hs folder
  3. 현재 폴더에서 파일 용량이 큰 순서대로 출력 du -h --max-depth=1 | sort -hr
    sudo du -h /home --max-depth=1 | sort -hr 이런식으로 점점 줄여가며 용량 찾아가면 됨.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment