Skip to content

Commit

Permalink
Start using docker containers
Browse files Browse the repository at this point in the history
  • Loading branch information
claudineisbezerra committed Dec 13, 2022
1 parent 0f0425a commit b9f62eb
Show file tree
Hide file tree
Showing 17 changed files with 9,239 additions and 6,124 deletions.
65 changes: 65 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.245.2/containers/docker-existing-docker-compose
// If you want to run as a non-root user in the container, see .devcontainer/docker-compose.yml.
{
"name": "Natours",
// Update the 'dockerComposeFile' list if you have more compose files or use different names.
// The .devcontainer/docker-compose.yml file contains any overrides you need/want to make.
"dockerComposeFile": [
"../docker-compose.dev.yaml"
],
// The 'service' property is the name of the service for the container that VS Code should
// use. Update this value and .devcontainer/docker-compose.yml to the real service name.
"service": "app",
// The optional 'workspaceFolder' property is the path VS Code should open by default when
// connected. This is typically a file mount in .devcontainer/docker-compose.yml
"workspaceFolder": "/home/node/app",
"customizations": {
"vscode": {
"extensions": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-vscode.vscode-typescript-tslint-plugin",
"msjsdiag.vscode-react-native",
"octref.vetur",
"PKief.material-icon-theme",
"ritwickdey.LiveServer",
"vuetifyjs.vuetify-vscode",
"johnpapa.vscode-peacock",
"pugbeautify.vscode-pugbeautify",
"firsttris.vscode-jest-runner",
"humao.rest-client",
"mikestead.dotenv",
"digitalbrainstem.javascript-ejs-support",
"dsznajder.es7-react-js-snippets",
"github.remotehub",
"equinusocio.vsc-material-theme",
"equinusocio.vsc-material-theme-icons",
"ms-vscode-remote.vscode-remote-extensionpack",
"vscode.remote-explorer",
"wayou.vscode-todo-highlight",
"naumovs.color-highlight",
"pranaygp.vscode-css-peek",
"github.vscode-pull-request-github",
"codezombiech.gitignore",
"eamodio.gitlens",
"kisstkondoros.vscode-gutter-preview",
"ms-kubernetes-tools.vscode-kubernetes-tools",
"ritwickdey.liveserver",
"mongodb.mongodb-vscode",
"analytic-signal.preview-pdf",
"redhat.vscode-yaml"
]
}
}
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment the next line if you want start specific services in your Docker Compose config.
// "runServices": [],
// Uncomment the next line if you want to keep your containers running after VS Code shuts down.
// "shutdownAction": "none",
// Uncomment the next line to run commands after the container is created - for example installing curl.
// "postCreateCommand": "apt-get update && apt-get install -y curl",
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
// "remoteUser": "vscode"
}
10 changes: 10 additions & 0 deletions .docker/start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash

npm install

#npm audit fix --force

#tail -f /dev/null -> Este comando 'mantem o container de pé'
# para evitar que o container termine após finalizar todos os comandos.
# Neste caso não estamos iniciando a aplicação (start).
tail -f /dev/null
1,640 changes: 1,640 additions & 0 deletions .docker/zsh/powerlevel10k/.p10k.zsh

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.history/
.docker/dbdata/
.docker/zsh
.devcontainer/
.git/
.github/
dist/
node_modules/
npm-debug.log
docker-compose.dev.yaml
docker-compose.prod.yaml
Dockerfile.dev
Dockerfile.prod
8 changes: 5 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
node_modules/
.cache/
*.env
node_modules/
.cache/
.docker/dbdata/
.docker/zsh/history/
*.env
22 changes: 22 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
// 1. Type of application to attach to
"type": "node",
// 2. Type of request. In this case 'attach'
"request": "attach",
// 3. Restart the debugger whenever it gets disconnected
"restart": true,
// 4. Port to connect to
"port": 9229,
// 5. Name of the configuration
"name": "Docker: Attach to Node",
// 6. Connect to /node directory of docker
"remoteRoot": "/home/node/app"
}
]
}
46 changes: 46 additions & 0 deletions Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# FROM node:16.16.0-slim
FROM node:18-slim

RUN apt update && apt install -y \
git \
gpg \
gnupg \
gpg-agent \
socat \
ca-certificates \
zsh \
curl \
wget \
fonts-powerline \
procps

RUN npm install -g nodemon

USER node
#Delimitar um usuário não root
#Princípio do mínimo privilégio

RUN mkdir -p /home/node/app

WORKDIR /home/node/app

RUN sh -c "$(wget -O- https://github.com/deluan/zsh-in-docker/releases/download/v1.1.2/zsh-in-docker.sh)" -- \
-t https://github.com/romkatv/powerlevel10k \
-p git \
-p git-flow \
-p https://github.com/zdharma-continuum/fast-syntax-highlighting \
-p https://github.com/zsh-users/zsh-autosuggestions \
-p https://github.com/zsh-users/zsh-completions \
-a 'export TERM=xterm-256color'

RUN echo '[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh' >> ~/.zshrc && \
echo 'HISTFILE=/home/node/zsh/.zsh_history' >> ~/.zshrc

# COPY --chown=node:node package.json package-lock.json ./
# RUN npm install -g nodemon
# RUN npm install
# RUN npm audit fix --force
# CMD [ "tail", "-f", "/dev/null" ]

# CMD é executado APÓS o container ter iniciado
CMD [ ".docker/start.sh" ]
35 changes: 35 additions & 0 deletions Dockerfile.prod
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
FROM node:16.16.0-slim as testing

USER node
RUN mkdir -p /home/node/app
WORKDIR /home/node/app

# COPY/NPM CI -> Feito em duas etapas para otimizar o processo de instalação. Neste caso há o uso/reaproveitamento de cache.
COPY --chown=node:node package.json package-lock.json ./
# RUN npm ci -> Faz instalações mais eficientes a partir do package-lock.json tanto prod quanto dev
RUN npm ci

COPY --chown=node:node . .
RUN npm run build

ENV NODE_ENV=production
CMD [ "npm", "run", "start:prod" ]

# Multi Stage - Descartar [Total ou em partes] os builds anteriores
FROM node:16.16.0-slim as production

USER node
RUN mkdir -p /home/node/app
WORKDIR /home/node/app

# Reaproveita os arquivos gerados no estágio anterior(testing)
COPY --from=testing --chown=node:node /home/node/app/package*.json ./
# --omit=dev significa que não será instalado (devDependencies)
RUN npm ci --omit=dev

COPY --from=testing --chown=node:node /home/node/app .

EXPOSE 3000

ENV NODE_ENV=production
CMD [ "npm", "run", "start:prod" ]
63 changes: 24 additions & 39 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,12 @@ const app = express();
// How to use it in routes
// req.app.get('ROLES')



app.enable('trust proxy');

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

// 1) GLOBAL MIDDLEWARES
// 1) GLOBAL MIDDLEWARES -
// Express middleware to enable CORS
app.use(cors());
// Access-Control-Allow-Origin *
Expand All @@ -55,32 +53,24 @@ app.options('*', cors());
// Serving static files
app.use(express.static(path.join(__dirname, 'public')));


// Set Content Security Policy in HTTP headers - Advanced configuration to avoid problems with mapbox and login at development
const CSP ={
defaultSrc: [
'https:',
'https://*.stripe.com/',
'https://*.mapbox.com/'
],
const CSP = {
defaultSrc: ['https:', 'https://*.stripe.com/', 'https://*.mapbox.com/'],
scriptSrc: [
'https://js.stripe.com/',
'https://checkout.stripe.com/',
'https://js.stripe.com/',
'https://edge-js.stripe.com',
'https://api.mapbox.com/'
'https://api.mapbox.com/',
],
scriptSrcElem: [
'https://api.mapbox.com/',
'https://js.stripe.com/',
'https://edge-js.stripe.com',
'https://checkout.stripe.com/',
'https://js.stripe.com/'
],
styleSrc: [
'https://api.mapbox.com/',
'https://fonts.googleapis.com/'
'https://js.stripe.com/',
],
styleSrc: ['https://api.mapbox.com/', 'https://fonts.googleapis.com/'],
connectSrc: [
'https://js.stripe.com/',
'https://checkout.stripe.com/',
Expand All @@ -90,36 +80,27 @@ const CSP ={
'http://127.0.0.1:*/',
'ws://127.0.0.1:*/',
'ws://tranquil-dawn-87413.herokuapp.com:*/',
'wss://tranquil-dawn-87413.herokuapp.com:*/'
],
imgSrc: [
'https://*.stripe.com'
'wss://tranquil-dawn-87413.herokuapp.com:*/',
],
fontSrc: [
'fonts.googleapis.com',
'fonts.gstatic.com'
],
frameSrc: [
'https://js.stripe.com',
'https://hooks.stripe.com'
]
}
imgSrc: ['https://*.stripe.com'],
fontSrc: ['fonts.googleapis.com', 'fonts.gstatic.com'],
frameSrc: ['https://js.stripe.com', 'https://hooks.stripe.com'],
};
app.use(
helmet
.contentSecurityPolicy({
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'", ...CSP.defaultSrc],
baseUri: ["'self'"],
connectSrc: ["'self'", ...CSP.connectSrc],
scriptSrc: ["'self'", "'unsafe-inline'", ...CSP.scriptSrc],
scriptSrcAttr: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'", "'unsafe-inline'", ...CSP.scriptSrc],
scriptSrcAttr: ["'self'", "'unsafe-inline'"],
scriptSrcElem: ["'self'", "'unsafe-inline'", ...CSP.scriptSrcElem],
styleSrc: ["'self'", 'https:', "'unsafe-inline'", ...CSP.styleSrc],
workerSrc: ["'self'", 'blob:'],
objectSrc: ["'none'"],
imgSrc: ["'self'", 'blob:', 'data:', ...CSP.imgSrc],
frameSrc: ["'self'",...CSP.frameSrc],
fontSrc: ["'self'", 'https:', 'data:', ...CSP.fontSrc]
frameSrc: ["'self'", ...CSP.frameSrc],
fontSrc: ["'self'", 'https:', 'data:', ...CSP.fontSrc],
},
})
);
Expand All @@ -133,12 +114,16 @@ if (process.env.NODE_ENV === 'development') {
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!'
message: 'Too many requests from this IP, please try again in an hour!',
});
app.use('/api', limiter);

// Stripe webhook, BEFORE express.raw() parser, because stripe needs the body as stream/buffer and not as JSON
app.post('/webhook-checkout', express.raw({type: 'application/json'}), bookingController.webhookStripeCheckout);
app.post(
'/webhook-checkout',
express.raw({ type: 'application/json' }),
bookingController.webhookStripeCheckout
);

// parse requests of content-type - application/json
app.use(express.json({ limit: '10kb' }));
Expand All @@ -164,8 +149,8 @@ app.use(
'ratingsAverage',
'maxGroupSize',
'difficulty',
'price'
]
'price',
],
})
);

Expand Down
Loading

0 comments on commit b9f62eb

Please sign in to comment.