반응형
안녕하세요! 둥오입니다.🌐
Node.js 환경변수 설정에서 문제를 겪고 계신가요? 오늘 가이드에서 초보자부터 숙련자까지 모두가 이해하기 쉽도록 상세히 설명해 드리겠습니다. 😊
목차 📑
1. 환경변수 기본 이해 🔍
1.1 환경변수란?
- 개념: 애플리케이션 실행 환경의 동적 값
- 용도: API 키, DB 연결 정보, 포트 설정 등
- 접근 방법: Node.js에서
process.env
객체 사용
1.2 기본 설정
// .env 파일 생성
NODE_ENV=development
PORT=3000
DB_URL=mongodb://localhost:27017
// Node.js에서 사용
require('dotenv').config();
console.log(process.env.NODE_ENV);
2. 주요 오류 및 해결방법 ⚡
2.1 undefined 값 문제
// 문제 상황
const apiKey = process.env.API_KEY; // undefined
// 해결방법 1: 기본값 설정
const apiKey = process.env.API_KEY || 'default_key';
// 해결방법 2: 필수 값 검증
if (!process.env.API_KEY) {
throw new Error('API_KEY is required');
}
2.2 dotenv 설정 오류
// 올바른 설정
const dotenv = require('dotenv');
dotenv.config({ path: '.env.local' }); // 커스텀 경로 지정 가능
// 다중 환경 설정
dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
3. 운영체제별 설정 가이드 💻
3.1 Windows
# 시스템 환경변수 설정
setx NODE_ENV "production" /M
setx PORT "3000" /M
# PowerShell에서 설정
$env:NODE_ENV = "production"
3.2 Linux/Mac
# 영구 설정
echo 'export NODE_ENV=production' >> ~/.bashrc
echo 'export PORT=3000' >> ~/.bashrc
source ~/.bashrc
# 임시 설정
export NODE_ENV=production
4. 보안 및 프로덕션 환경 🔒
4.1 보안 설정
// 환경변수 암호화
const crypto = require('crypto');
const algorithm = 'aes-256-ctr';
const secretKey = process.env.SECRET_KEY;
const encrypt = (text) => {
const cipher = crypto.createCipher(algorithm, secretKey);
return cipher.update(text, 'utf8', 'hex') + cipher.final('hex');
};
// .gitignore 설정
.env
.env.local
.env.*.local
4.2 프로덕션 환경 설정
// config/index.js
const config = {
development: {
api: 'http://localhost:3000',
db: 'mongodb://localhost:27017'
},
production: {
api: process.env.API_URL,
db: process.env.DB_URL
}
}[process.env.NODE_ENV || 'development'];
5. 고급 설정 및 트러블슈팅 🛠️
5.1 환경변수 유효성 검사
const Joi = require('joi');
const envSchema = Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production')
.required(),
PORT: Joi.number().default(3000),
API_KEY: Joi.string().required()
}).unknown();
const { error } = envSchema.validate(process.env);
if (error) throw new Error(`환경변수 검증 실패: ${error.message}`);
5.2 동적 환경변수 관리
class EnvManager {
constructor() {
this.cache = new Map();
}
get(key, defaultValue) {
if (!this.cache.has(key)) {
this.cache.set(key, process.env[key] || defaultValue);
}
return this.cache.get(key);
}
}
module.exports = new EnvManager();
6. 자주 묻는 질문 💭
Q: 환경변수가 변경되어도 반영이 안돼요.
A: 서버를 재시작하거나 다음 명령어로 노드 프로세스를 재시작하세요:
pm2 restart all # PM2 사용 시
nodemon # 개발 환경
Q: 여러 환경에서 다른 설정을 써야 해요.
A: 환경별 .env 파일을 만들어 관리하세요:
.env.development
.env.staging
.env.production
마무리 👋
오늘은 이만 마치겠습니다.😊
반응형
'컴퓨터 & 스마트폰' 카테고리의 다른 글
크롬 브라우저 느려짐 완벽 해결 가이드 (0) | 2025.01.19 |
---|---|
OneDrive 동기화 충돌 해결 가이드 (0) | 2025.01.18 |
Java 개발환경 충돌 문제 해결 가이드 (0) | 2025.01.18 |
MS Office 365 동기화 실패 해결 방법 (0) | 2025.01.18 |
Docker 컨테이너 문제 해결 방법 (0) | 2025.01.17 |
댓글