프로젝트를 배포하던 중 AWS EC2에서 메모리 부족 현상으로 ssh 접속이 안되는 상황이 발생했다...
(프리티어 사용중)
프리티어로 사용하게 되는 t2.micro 인스턴스 유형은 램이 1GB이기 때문에 메모리 부족현상이 일어날 수 있다!
=> swap file을 이용하여 swap memory 할당을 해보자!
(현재 생성한 EC2는 ubuntu 환경임)
EC2 램이 가득 찼기 때문에 실제 디스크의 용량을 이용하여 부족한 메모리를 대체할 공간을 swap memory 라고 함!
=> 보통 swap memory는 할당된 메모리의 2배를 추천하고 있다고 함!
스왑 메모리는 RAM을 대신하는 것이 아니라, RAM이 부족할 때 임시로 사용하는 비상 메커니즘으로 생각하는게 좋음
=> 디스크에 저장된 스왑 메모리는 RAM 보다 훨씬 느리고 로그 파일 같은 기타 중요 데이터는 디스크에 저장될 텐데 너무 크게 설정하면 이를 저장할 디스크 공간이 부족할 수 있기 때문
우선 이를 위해 ssh로 내 EC2에 접속하자!!
swapfile 생성
sudo dd if=/dev/zero of=/swapfile bs=128M count=16
dd 명령어는 유닉스 및 리눅스 시스템에서 데이터 복사 및 변환을 위한 명령어이다!
(주로 원시 데이터 복사에 사용됨)
if는 "input file"의 약자임
=> /dev/zero 는 무한한 null 바이트(0)로 구성된 가상 파일로, 원하는 크기만큼의 0값을 포함한 데이터를 생성할 때 사용됨
(현재의 경우, swap file에 0으로 채워진 데이터를 생성하기 위해 사용됨)
/dev/zero는 리눅스와 유닉스 계열 운영체제에서 제공하는 특수 파일(special file)로 이 파일은 파일 시스템에 실제로 존재하는 일반적인 파일이 아니라, 커널이 메모리 상에서 가상으로 관리하는 장치 파일임
=> 실제 저장 공간을 차지하지 않고 그에 대한 요청이 있을 때마다 커널이 필요한 데이터를 동적으로 생성하여 제공
of는 "output file"의 약자임
=> /swapfile 은 생성할 swap file의 경로 및 이름을 지정함
(/swapfile 이라는 이름의 파일을 루트 디렉토리에 생성하고 있음)
bs는 "block size"의 약자임
=> 128M는 블록 크기를 128 메가바이트로 설정하겠다는 뜻임
(한 번에 128MB씩 파일을 작성하게 됨)
count는 복사할 블록의 개수를 지정함
=> 16은 128MB 블록을 16번 생성하겠다는 의미임
(최종적으로는 128MB x 16 = 목표했던 2GB 크기의 파일이 생성됨)
swapfile에 접근할 수 있는 권한을 설정
sudo chmod 600 /swapfile
read/write 가 가능하도록 chmod 600으로 설정해줌
swapfile을 추가할 swap 공간을 생성
sudo mkswap /swapfile
mkswap은 Make swap의 약자임
(swapfile을 swap 파티션으로 변환하는 유틸리티)
위에서 생성한 swapfile은 단순히 데이터를 저장할 수 있는 공간일 뿐, 실제 스왑으로 사용하려면 이 작업을 거쳐야함!
=> mkswap을 통해 swapfile을 스왑 데이터가 저장될 수 있는 구조로 설정함
swapfile을 swap memory에 추가
sudo swapon /swapfile
swapon 명령어를 통해 swapfile을 스왑 메모리로 활성화하여 시스템에서 실제로 사용할 수 있도록 함
(램이 부족할 때 스왑 파일이 사용됨 => 시스템이 메모리 사용을 효율적으로 관리하기 위해 미리 스왑을 사용할 수 있어서 메모리가 남아도 스왑 공간이 사용될 수 있음!)
mkswap 과 swapon 이 헷갈릴 수 있는데
mkswap은 스왑 파일에 필요한 메타데이터를 추가하고 파일을 올바른 포맷으로 준비하는 과정임
=> mkswap 없이 swapon을 사용하면 스왑 파일이 스왑 영역으로 인식되지 않고, 실제로 사용할 수 없음!!
swapfile 활성화
// vi 에디터로 열기
sudo vi /etc/fstab
// 파일의 맨 끝에 아래 명령어 작성
/swapfile swap swap defaults 0 0
/etc/fstab 은 파일시스템 정보를 저장하는 곳임
=> 파티션 변경 및 디스크 추가 시에는 이 파일에 등록해야 자동으로 마운트가 가능해짐
(시스템 부팅 시 자동으로 스왑 파일이나 파티션을 활성화하고 사용 가능하도록 하기 위해서 => 매번 수동으로 swapon 명령어 입력할 필요 X)
코드를 살펴보면
/swapfile 을 통해 스왑 파일의 경로를 지정하고
(이 경우 스왑 파일이 /swapfile 위치에 있다는 의미)
처음 나오는 swap을 통해 파일 시스템의 타입을 지정하고
(스왑 파일이나 스왑 파티션의 경우 이 필드는 swap으로 설정됨 => 시스템에 이 파일 시스템이 스왑 용도로 사용된다고 알려줌)
두 번째로 나오는 swap은 파일 시스템의 마운트 지점을 지정하는 부분임
(스왑 파일은 이 필드가 실제로 필요 X => 시스템에 스왑 영역인걸 그냥 알려주는 용도)
defaults는 마운트 옵션을 지정하는건데 기본 옵션을 사용한다는 의미로 스왑 파일의 경우 이 옵션이 보통 사용됨
첫 번째 0은 파일 시스템 dump 순서를 지정함
(백업 소프트웨어가 파일 시스템을 덤프 할 순서를 정하는데 사용하는데 스왑 파일에는 적용되지 않으며 보통 0으로 설정)
=> 스왑 파일의 목적 자체가 램이 부족할 때 사용하는 일시적인 데이터 저장소이므로 굳이 덤프할 필요가 X
두 번째 0은 파일 시스템 검사의 순서를 지정함
(검사가 필요할 때의 순서를 정하는데 스왑 파일에는 적용되지 않으면 보통 0으로 설정)
메모리 할당 확인
'Infra > AWS' 카테고리의 다른 글
Docker로 EC2에 MySQL 띄우기 (6) | 2024.09.03 |
---|---|
Permissions for '*.pem' are too open 에러 해결 (0) | 2024.04.06 |