如何使用多个package.json

时间:2019-05-14 05:41:30

标签: node.js docker

我有一个旧应用程序,试图将其移植到Docker。我不确定如何让Docker复制这两个Package.json并运行它们。

旧于:

Socket.io '0.9.14'
Node '0.10'

这是我的项目目录结构

/ code / my_socketio /

在此 my_socketio 目录中:

node_modules
recipes (docker recipes)
server.js (socket.io server code)
Dockerfile
.dockerignore

在上面的 node_modules 目录中,我有多个文件和两个package.json:

socket.io/package.json
forever/package.json

socket.io/package.json代码:

    {
  "name": "socket.io",
  "version": "0.9.14",
  "description": "Real-time apps made cross-browser & easy with a WebSocket-like API",
  "homepage": "http://socket.io",
  "keywords": [
    "websocket",
    "socket",
    "realtime",
    "socket.io",
    "comet",
    "ajax"
  ],
  "author": {
    "name": "Guillermo Rauch",
    "email": "guillermo@learnboost.com"
  },
  "contributors": [
    {
      "name": "Guillermo Rauch",
      "email": "rauchg@gmail.com"
    },
    {
      "name": "Arnout Kazemier",
      "email": "info@3rd-eden.com"
    },
    {
      "name": "Vladimir Dronnikov",
      "email": "dronnikov@gmail.com"
    },
    {
      "name": "Einar Otto Stangvik",
      "email": "einaros@gmail.com"
    }
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/LearnBoost/socket.io.git"
  },
  "dependencies": {
    "socket.io-client": "0.9.11",
    "policyfile": "0.0.4",
    "base64id": "0.1.0",
    "redis": "0.7.3"
  },
  "devDependencies": {
    "expresso": "0.9.2",
    "should": "*",
    "benchmark": "0.2.2",
    "microtime": "0.1.3-1",
    "colors": "0.5.1"
  },
  "optionalDependencies": {
    "redis": "0.7.3"
  },
  "main": "index",
  "engines": {
    "node": ">= 0.4.0"
  },
  "scripts": {
    "test": "make test",
    "start": "node index.js"
  },
  "readme": "# Socket.IO\n\nSocket.IO is a Node.JS project that makes WebSockets and realtime possible in\nall browsers. It also enhances WebSockets by providing built-in multiplexing,\nhorizontal scalability, automatic JSON encoding/decoding, and more.\n\n## How to Install\n\n```bash\nnpm install socket.io\n```\n\n## How to use\n\nFirst, require `socket.io`:\n\n```js\nvar io = require('socket.io');\n```\n\nNext, attach it to a HTTP/HTTPS server. If you're using the fantastic `express`\nweb framework:\n\n#### Express 3.x\n\n```js\nvar app = express()\n  , server = require('http').createServer(app)\n  , io = io.listen(server);\n\nserver.listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.emit('news', { hello: 'world' });\n  socket.on('my other event', function (data) {\n    console.log(data);\n  });\n});\n```\n\n#### Express 2.x\n\n```js\nvar app = express.createServer()\n  , io = io.listen(app);\n\napp.listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.emit('news', { hello: 'world' });\n  socket.on('my other event', function (data) {\n    console.log(data);\n  });\n});\n```\n\nFinally, load it from the client side code:\n\n```html\n<script src=\"/socket.io/socket.io.js\"></script>\n<script>\n  var socket = io.connect('http://localhost');\n  socket.on('news', function (data) {\n    console.log(data);\n    socket.emit('my other event', { my: 'data' });\n  });\n</script>\n```\n\nFor more thorough examples, look at the `examples/` directory.\n\n## Short recipes\n\n### Sending and receiving events.\n\nSocket.IO allows you to emit and receive custom events.\nBesides `connect`, `message` and `disconnect`, you can emit custom events:\n\n```js\n// note, io.listen(<port>) will create a http server for you\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  io.sockets.emit('this', { will: 'be received by everyone' });\n\n  socket.on('private message', function (from, msg) {\n    console.log('I received a private message by ', from, ' saying ', msg);\n  });\n\n  socket.on('disconnect', function () {\n    io.sockets.emit('user disconnected');\n  });\n});\n```\n\n### Storing data associated to a client\n\nSometimes it's necessary to store data associated with a client that's\nnecessary for the duration of the session.\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.on('set nickname', function (name) {\n    socket.set('nickname', name, function () { socket.emit('ready'); });\n  });\n\n  socket.on('msg', function () {\n    socket.get('nickname', function (err, name) {\n      console.log('Chat message by ', name);\n    });\n  });\n});\n```\n\n#### Client side\n\n```html\n<script>\n  var socket = io.connect('http://localhost');\n\n  socket.on('connect', function () {\n    socket.emit('set nickname', prompt('What is your nickname?'));\n    socket.on('ready', function () {\n      console.log('Connected !');\n      socket.emit('msg', prompt('What is your message?'));\n    });\n  });\n</script>\n```\n\n### Restricting yourself to a namespace\n\nIf you have control over all the messages and events emitted for a particular\napplication, using the default `/` namespace works.\n\nIf you want to leverage 3rd-party code, or produce code to share with others,\nsocket.io provides a way of namespacing a `socket`.\n\nThis has the benefit of `multiplexing` a single connection. Instead of\nsocket.io using two `WebSocket` connections, it'll use one.\n\nThe following example defines a socket that listens on '/chat' and one for\n'/news':\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nvar chat = io\n  .of('/chat')\n  .on('connection', function (socket) {\n    socket.emit('a message', { that: 'only', '/chat': 'will get' });\n    chat.emit('a message', { everyone: 'in', '/chat': 'will get' });\n  });\n\nvar news = io\n  .of('/news');\n  .on('connection', function (socket) {\n    socket.emit('item', { news: 'item' });\n  });\n```\n\n#### Client side:\n\n```html\n<script>\n  var chat = io.connect('http://localhost/chat')\n    , news = io.connect('http://localhost/news');\n\n  chat.on('connect', function () {\n    chat.emit('hi!');\n  });\n\n  news.on('news', function () {\n    news.emit('woot');\n  });\n</script>\n```\n\n### Sending volatile messages.\n\nSometimes certain messages can be dropped. Let's say you have an app that\nshows realtime tweets for the keyword `bieber`. \n\nIf a certain client is not ready to receive messages (because of network slowness\nor other issues, or because he's connected through long polling and is in the\nmiddle of a request-response cycle), if he doesn't receive ALL the tweets related\nto bieber your application won't suffer.\n\nIn that case, you might want to send those messages as volatile messages.\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  var tweets = setInterval(function () {\n    getBieberTweet(function (tweet) {\n      socket.volatile.emit('bieber tweet', tweet);\n    });\n  }, 100);\n\n  socket.on('disconnect', function () {\n    clearInterval(tweets);\n  });\n});\n```\n\n#### Client side\n\nIn the client side, messages are received the same way whether they're volatile\nor not.\n\n### Getting acknowledgements\n\nSometimes, you might want to get a callback when the client confirmed the message\nreception.\n\nTo do this, simply pass a function as the last parameter of `.send` or `.emit`.\nWhat's more, when you use `.emit`, the acknowledgement is done by you, which\nmeans you can also pass data along:\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.on('ferret', function (name, fn) {\n    fn('woot');\n  });\n});\n```\n\n#### Client side\n\n```html\n<script>\n  var socket = io.connect(); // TIP: .connect with no args does auto-discovery\n  socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!\n    socket.emit('ferret', 'tobi', function (data) {\n      console.log(data); // data will be 'woot'\n    });\n  });\n</script>\n```\n\n### Broadcasting messages\n\nTo broadcast, simply add a `broadcast` flag to `emit` and `send` method calls.\nBroadcasting means sending a message to everyone else except for the socket\nthat starts it.\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.broadcast.emit('user connected');\n  socket.broadcast.json.send({ a: 'message' });\n});\n```\n\n### Rooms\n\nSometimes you want to put certain sockets in the same room, so that it's easy\nto broadcast to all of them together.\n\nThink of this as built-in channels for sockets. Sockets `join` and `leave`\nrooms in each socket.\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.join('justin bieber fans');\n  socket.broadcast.to('justin bieber fans').emit('new fan');\n  io.sockets.in('rammstein fans').emit('new non-fan');\n});\n```\n\n### Using it just as a cross-browser WebSocket\n\nIf you just want the WebSocket semantics, you can do that too.\nSimply leverage `send` and listen on the `message` event:\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.sockets.on('connection', function (socket) {\n  socket.on('message', function () { });\n  socket.on('disconnect', function () { });\n});\n```\n\n#### Client side\n\n```html\n<script>\n  var socket = io.connect('http://localhost/');\n  socket.on('connect', function () {\n    socket.send('hi');\n\n    socket.on('message', function (msg) {\n      // my msg\n    });\n  });\n</script>\n```\n\n### Changing configuration\n\nConfiguration in socket.io is TJ-style:\n\n#### Server side\n\n```js\nvar io = require('socket.io').listen(80);\n\nio.configure(function () {\n  io.set('transports', ['websocket', 'flashsocket', 'xhr-polling']);\n});\n\nio.configure('development', function () {\n  io.set('transports', ['websocket', 'xhr-polling']);\n  io.enable('log');\n});\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 Guillermo Rauch &lt;guillermo@learnboost.com&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
  "readmeFilename": "Readme.md",
  "_id": "socket.io@0.9.14",
  "dist": {
    "shasum": "dac4424bb73bcce9c0309e3443b7a63c62784ef2"
  },
  "_from": "socket.io@",
  "_resolved": "https://registry.npmjs.org/socket.io/-/socket.io-0.9.14.tgz"
}

Dockerfile:

FROM mhart/alpine-node:0.10 AS build
WORKDIR /srv
ADD package.json .
RUN npm install
ADD . .

FROM mhart/alpine-node:base-0.10
COPY --from=build /srv .
EXPOSE 8080
CMD ["node", "index.js"]

forever / package.json代码:

    {
  "name": "forever",
  "preferGlobal": "true",
  "description": "A simple CLI tool for ensuring that a given node script runs continuously (i.e. forever)",
  "version": "0.10.7",
  "author": {
    "name": "Nodejitsu Inc.",
    "email": "info@nodejitsu.com"
  },
  "maintainers": [
    {
      "name": "indexzero",
      "email": "charlie@nodejitsu.com"
    },
    {
      "name": "mmalecki",
      "email": "maciej@nodejitsu.com"
    },
    {
      "name": "avianflu",
      "email": "charlie@charlieistheman.com"
    }
  ],
  "repository": {
    "type": "git",
    "url": "http://github.com/nodejitsu/forever.git"
  },
  "keywords": [
    "cli",
    "fault tolerant",
    "sysadmin",
    "tools"
  ],
  "dependencies": {
    "colors": "0.6.0-1",
    "cliff": "0.1.8",
    "flatiron": "0.3.5",
    "forever-monitor": "1.2.1",
    "nconf": "0.6.7",
    "nssocket": "~0.5.1",
    "optimist": "0.4.0",
    "pkginfo": "0.3.0",
    "timespan": "2.0.1",
    "watch": "0.7.0",
    "utile": "0.1.7",
    "winston": "0.7.1"
  },
  "devDependencies": {
    "broadway": "0.2.x",
    "eventemitter2": "0.4.x",
    "request": "2.x.x",
    "vows": "0.7.x"
  },
  "bin": {
    "forever": "./bin/forever",
    "foreverd": "./bin/foreverd"
  },
  "main": "./lib/forever",
  "scripts": {
    "test": "vows test/**/*-test.js --spec -i"
  },
  "engines": {
    "node": ">= 0.8.x"
  },
  "readme": "# forever [![Build Status](https://secure.travis-ci.org/nodejitsu/forever.png)](http://travis-ci.org/nodejitsu/forever)\n\nA simple CLI tool for ensuring that a given script runs continuously (i.e. forever).\n\n## Installation\n\n``` bash\n  $ [sudo] npm install forever -g\n```\n\n**Note:** If you are using forever _programatically_ you should install [forever-monitor][0].\n\n``` bash\n  $ cd /path/to/your/project\n  $ [sudo] npm install forever-monitor\n```\n\n## Usage\nThere are two distinct ways to use forever: through the command line interface, or by requiring the forever module in your own code. **Note:** If you are using forever _programatically_ you should install [forever-monitor][0].\n\n### Using forever from the command line\nYou can use forever to run any kind of script continuously (whether it is written in node.js or not). The usage options are simple:\n\n```\n  $ forever --help\n  usage: forever [action] [options] SCRIPT [script-options]\n\n  Monitors the script specified in the current process or as a daemon\n\n  actions:\n    start               Start SCRIPT as a daemon\n    stop                Stop the daemon SCRIPT\n    stopall             Stop all running forever scripts\n    restart             Restart the daemon SCRIPT\n    restartall          Restart all running forever scripts\n    list                List all running forever scripts\n    config              Lists all forever user configuration\n    set <key> <val>     Sets the specified forever config <key>\n    clear <key>         Clears the specified forever config <key>\n    logs                Lists log files for all forever processes\n    logs <script|index> Tails the logs for <script|index>\n    columns add <col>   Adds the specified column to the output in `forever list`\n    columns rm <col>    Removed the specified column from the output in `forever list`\n    columns set <cols>  Set all columns for the output in `forever list`\n    cleanlogs           [CAREFUL] Deletes all historical forever log files\n\n  options:\n    -m  MAX          Only run the specified script MAX times\n    -l  LOGFILE      Logs the forever output to LOGFILE\n    -o  OUTFILE      Logs stdout from child script to OUTFILE\n    -e  ERRFILE      Logs stderr from child script to ERRFILE\n    -p  PATH         Base path for all forever related files (pid files, etc.)\n    -c  COMMAND      COMMAND to execute (defaults to node)\n    -a, --append     Append logs\n    -f, --fifo       Stream logs to stdout\n    -n, --number     Number of log lines to print\n    --pidFile        The pid file\n    --sourceDir      The source directory for which SCRIPT is relative to\n    --minUptime      Minimum uptime (millis) for a script to not be considered \"spinning\"\n    --spinSleepTime  Time to wait (millis) between launches of a spinning script.\n    --plain          Disable command line colors\n    -d, --debug      Forces forever to log debug output\n    -v, --verbose    Turns on the verbose messages from Forever\n    -s, --silent     Run the child script silencing stdout and stderr\n    -w, --watch      Watch for file changes\n    --watchDirectory Top-level directory to watch from\n    -h, --help       You're staring at it\n\n  [Long Running Process]\n    The forever process will continue to run outputting log messages to the console.\n    ex. forever -o out.log -e err.log my-script.js\n\n  [Daemon]\n    The forever process will run as a daemon which will make the target process start\n    in the background. This is extremely useful for remote starting simple node.js scripts\n    without using nohup. It is recommended to run start with -o -l, & -e.\n    ex. forever start -l forever.log -o out.log -e err.log my-daemon.js\n        forever stop my-daemon.js\n```\n\nThere are [several examples][1] designed to test the fault tolerance of forever. Here's a simple usage example:\n\n``` bash\n  $ forever -m 5 examples/error-on-timer.js\n```\n\n## Using forever module from node.js\nIn addition to using a Forever object, the forever module also exposes some useful methods. Each method returns an instance of an EventEmitter which emits when complete. See the [forever cli commands][2] for sample usage.\n\n**Remark:** As of `forever@0.6.0` processes will not automatically be available in `forever.list()`. In order to get your processes into `forever.list()` or `forever list` you must instantiate the `forever` socket server:\n\n``` js\n  forever.startServer(child);\n```\n\n### forever.load (config)\n_Synchronously_ sets the specified configuration (config) for the forever module. There are two important options:\n\n* root:    Directory to put all default forever log files\n* pidPath: Directory to put all forever *.pid files\n\n### forever.start (file, options)\nStarts a script with forever.\n\n### forever.startDaemon (file, options)\nStarts a script with forever as a daemon. WARNING: Will daemonize the current process.\n\n### forever.stop (index)\nStops the forever daemon script at the specified index. These indices are the same as those returned by forever.list(). This method returns an EventEmitter that raises the 'stop' event when complete.\n\n### forever.stopAll (format)\nStops all forever scripts currently running. This method returns an EventEmitter that raises the 'stopAll' event when complete.\n\n### forever.list (format, callback)\nReturns a list of metadata objects about each process that is being run using forever. This method is synchronous and will return the list of metadata as such. Only processes which have invoked `forever.startServer()` will be available from `forever.list()`\n\n### forever.tail (target, options, callback)\nResponds with the logs from the target script(s) from `tail`. There are two important options:\n\n* `length` (numeric): is is used as the `-n` parameter to `tail`.\n* `stream` (boolean): is is used as the `-f` parameter to `tail`.\n\n### forever.cleanUp ()\nCleans up any extraneous forever *.pid files that are on the target system. This method returns an EventEmitter that raises the 'cleanUp' event when complete.\n\n### forever.cleanLogsSync (processes)\nRemoves all log files from the root forever directory that do not belong to current running forever processes.\n\n## Run Tests\n\n``` bash\n  $ npm test\n```\n\n#### License: MIT\n#### Author: [Charlie Robbins](http://github.com/indexzero)\n#### Contributors: [Fedor Indutny](http://github.com/indutny), [James Halliday](http://substack.net/), [Charlie McConnell](http://github.com/avianflu), [Maciej Malecki](http://github.com/mmalecki), [John Lancaster](http://jlank.com)\n\n[0]: http://github.com/nodejitsu/forever-monitor\n[1]: http://github.com/nodejitsu/forever-monitor/tree/master/examples\n[2]: https://github.com/nodejitsu/forever/blob/master/lib/forever/cli.js\n",
  "readmeFilename": "README.md",
  "_id": "forever@0.10.7",
  "dist": {
    "shasum": "4c59156714cef92011f5a0a238846b64552ecc53"
  },
  "_from": "forever@",
  "_resolved": "https://registry.npmjs.org/forever/-/forever-0.10.7.tgz"
}

1 个答案:

答案 0 :(得分:2)

您可以使用Docker RUN运行shell命令。 dockerfile的外观应与此类似,具体取决于您的目录结构

FROM mhart/alpine-node:0.10 AS build
WORKDIR /srv
ADD . .

#Do the socket.io installation
RUN cd socket.io
RUN npm install

#Do the forever installation
RUN cd ..
RUN cd forever
RUN npm install



FROM mhart/alpine-node:base-0.10
COPY --from=build /srv .
EXPOSE 8080
CMD ["node", "index.js"]