
some-other-api 는 우리의 소유가 아니기에 GET, POST 등의 요청을 보내야 한다

// app.js
mongoose.connect(
'mongodb://localhost:27017/favorites',
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
app.listen(3000);
}
}
);
localhost 를 추후 mongodb container 주소로 변결할 것이다// app.js
app.get('/favorites', async (req, res) => {
const favorites = await Favorite.find();
res.status(200).json({
favorites: favorites,
});
});
mongodb 에 저장된 데이터를 조회하는 코드app.post('/favorites', async (req, res) => {
const favName = req.body.name;
const favType = req.body.type;
const favUrl = req.body.url;
try {
if (favType !== 'movie' && favType !== 'character') {
throw new Error('"type" should be "movie" or "character"!');
}
const existingFav = await Favorite.findOne({ name: favName });
if (existingFav) {
throw new Error('Favorite exists already!');
}
} catch (error) {
return res.status(500).json({ message: error.message });
}
const favorite = new Favorite({
name: favName,
type: favType,
url: favUrl,
});
try {
await favorite.save();
res
.status(201)
.json({ message: 'Favorite saved!', favorite: favorite.toObject() });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
});
favorite 을 MongoDB 에 저장하는 코드app.get('/movies', async (req, res) => {
try {
const response = await axios.get('https://swapi.dev/api/films');
res.status(200).json({ movies: response.data });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
});
app.get('/people', async (req, res) => {
try {
const response = await axios.get('https://swapi.dev/api/people');
res.status(200).json({ people: response.data });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
});
FROM node
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
CMD ["node", "app.js"]
node.js 를 dockerize 하기 위한 Dockerfiledocker build -t favorites-node .docker run --name favorties -d --rm -p 3000:3000 favorites-nodedocker ps 를 통해 컨테이너를 조회하면, 실행됐어야 할 컨테이너가 없다https://www.mongodb.com/ko-kr/docs/manual/installation/
app.js 를 다시 살펴보자mongoose.connect(
'mongodb://localhost:27017/swfavorites',
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
app.listen(3000);
}
}
);
localhost 는 컨테이너 내의 MongoDB 에 연결하겠다는 의미mongoose.connect(
'mongodb://host.docker.internal:27017/swfavorites',
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
app.listen(3000);
}
}
);
host.docker.internal 은 도커에 의해 인식된다docker run -d --name mongodb mongo
host.docker.internal 이 아닌, 방금 실행한 컨테이너에 연결docker container inspect 을 이용해 컨테이너 정보 확인docker container inspect mongodb...
"NetworkSettings": {
"Bridge": "",
"SandboxID": "bf47a48bb4d393e54c32c297d376fed272bc39f5a95e6f6837dafeb79868ea54",
"SandboxKey": "/var/run/docker/netns/bf47a48bb4d3",
"Ports": {
"27017/tcp": null
},
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "6df40b7bef8a10abc10ea04538339e72c7293becb5f5e1aeb08592fcdd418420",
"Gateway": "172.17.0.1",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"MacAddress": "02:42:ac:11:00:02",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null,
"NetworkID": "c925a9282efacea3ab9a983ff08dec640fa1e8ce9db5c9df83f8e8b4b2615045",
"EndpointID": "6df40b7bef8a10abc10ea04538339e72c7293becb5f5e1aeb08592fcdd418420",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"DNSNames": null
}
}
}
...
172.12.0.2 가 mongodb 컨테이너의 IP 다mongoose.connect(
'mongodb://172.17.0.2:27017/swfavorites',
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
app.listen(3000);
}
}
);
docker run 시 --network 옵션을 통해 구성한다docker run --network <NETWORK_NAME> <IMAGE_NAME>docker network create favorites-net
docker network ls
docker run -d --name mongodb --network favorites-net mongo
// app.js
mongoose.connect(
'mongodb://mongodb:27017/swfavorites',
{ useNewUrlParser: true },
(err) => {
if (err) {
console.log(err);
} else {
app.listen(3000);
}
}
);
docker build -t favorites-node .docker run --name favorites --network favorites-net -d --rm -p 3000:3000 favorites-nodedocker ps-p 옵션 없이도 컨테이너에서 27017에 정확히 접속할 수 있었다.-p 옵션은 컨테이너 외부에서 접속하기 위해 사용하는 것-p 를 통한 노출이 필요없다