I am trying to deploy my node app with Docker.Here is my node app:
var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');
var mongoose =require('mongoose');
app.use(express.static("./app"));
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'root',
database: 'node_db'
});
app.set('port',8080);
app.set('views',path.join(__dirname,'views'));
app.set('view engine','jade');
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.sendfile('app/index.html');
});
app.get('/getAllBlogs', function (req, res) {
pool.getConnection(function (err, connection) {
var sql = mysql.format("select * from blogs");
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
res.send(error);
}
res.send(results);
});
});
});
app.get('/getBlog/:id', function(req,res){
console.log(req.params.id);
pool.getConnection(function (err, connection) {
var sql = mysql.format("select * from blogs where id=?", [req.params.id]);
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
res.status(200).send(error);
}
res.send(results[0])
});
});
});
app.listen(app.get('port'));
console.log('~~Server Runnign on port localhost:'+app.get('port')+'~~');
Here is my Docker file:
FROM node:boron
# Create app directory
RUN mkdir -p /home/sameera/Desktop/test/app
WORKDIR /home/sameera/Desktop/test/app
# Install app dependencies
COPY package.json /home/sameera/Desktop/test/app
RUN npm install
# Bundle app source
COPY . /home/sameera/Desktop/test/app
EXPOSE 8080
CMD [ "npm", "start" ]
The docker file built successfully and when i run below command it is running properly.
docker run -p 49160:8080 img
But when i try to load a page with data that is using mysql it is
giving an error:
connection.query(sql, function (error, results, fields) {
^
TypeError: Cannot read property 'query' of undefined
}
I guess the problem is with that i can't connect to mysql with this container since i am not install or use any mysql related commands in docker file.When i remove all my sql connection and related code it is not giving any error and running properly.I am using ubuntu 14.04
Best Answer
You can use below code if pool is not required:
Result will be something like that:
But if the pool is necessary and you want to use pool then you should try below code:
Result wll be like that: