投稿時間:2021-12-22 23:33:47 RSSフィード2021-12-22 23:00 分まとめ(38件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita ConoHaを使ってPythonでWEB情報を取得するお話 https://qiita.com/cheblo_azu/items/b1180f8b848466cf0bb1 2021-12-22 22:50:38
js JavaScriptタグが付けられた新着投稿 - Qiita 【Jest】new Date()をモック化する方法 https://qiita.com/pg_yamaton/items/2a8f6fa59e5ea145bc87 【Jest】newDateをモック化する方法この記事の概要newDateはテスト時には固定の値を返して欲しいのでその方法を記載した簡易メモ方法useFakeTimerssetSystemTimeを使うhogespectsconstmockDatenewDatejestuseFakeTimersjestsetSystemTimemockDate多分Jest公式通りの一番簡単なベストな方法※全体に影響するのでafterEachでjestuseRealTimersしておく方法globalのDateにspyhogespectsconstmockDatenewDateconstspyjestspyOnglobalDatemockImplementationgtmockDateasunknownasstring方法spy用の関数を別途用意dateutlstsexportfunctiongetNowreturnnewDatehogespectsimportasDateUtilsfromdateutilsconstmockDatenewDateconstspyjestspyOnDateUtilsgetNowmockReturnValuemockDate※newDateを使うのはgetNowだけ。 2021-12-22 22:07:52
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) getElementByIdとquerySelectorの違い https://teratail.com/questions/375132?rss=all getElementByIdとquerySelectorの違いpタグを複数作り、各idにカウンタ変数を代入しました。 2021-12-22 22:45:25
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) drawer.jsをPCサイズの時も有効にしたい https://teratail.com/questions/375131?rss=all 2021-12-22 22:36:02
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) wordpressで2つのjQueryのプラグインをfunction.phpで読み込みたいのですが、2つ目が動きません。 https://teratail.com/questions/375130?rss=all wordpressでつのjQueryのプラグインをfunctionphpで読み込みたいのですが、つ目が動きません。 2021-12-22 22:33:30
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 複数の数列から同じ順番の要素を取り出したい https://teratail.com/questions/375129?rss=all ただfor文のようにつずつ要素を取り出したいと思っています。 2021-12-22 22:28:50
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 最小二乗法を使った近似直線の書き方 https://teratail.com/questions/375128?rss=all 最小二乗法を使った近似直線の書き方前提・実現したいこと近似直線を描く岩手県と秋田県の人口と死亡者数の相関を調べるためのグラフを製作しており、近似直線を書きたいのですが、近似直線がつしか書けません。 2021-12-22 22:09:17
Ruby Rubyタグが付けられた新着投稿 - Qiita 他業種からプログラミング講座に挑戦してみて見えたこと(課題) https://qiita.com/chi71/items/5d2cd101b74c0ed49d92 乗り越えたと思って実はできていなかったこと見えていなかった部分・調べることで、その場で解決して変な自信や満足感を得ているが、根本的に理解できていない。 2021-12-22 22:40:44
Ruby Rubyタグが付けられた新着投稿 - Qiita has_one関連付けのbuild_associationメソッドは暗黙的にレコードを削除する https://qiita.com/evitch/items/7a3204e540112811b3e3 hasone関連付けのbuildassociationメソッドは暗黙的にレコードを削除する環境RailsRubyMySQL前提userrbclassUserltApplicationRecordhasoneitemdependentdestroyenditemrbclassItemltApplicationRecordbelongstouserend解説ActiveRecordでhasone関連付けを利用すると、以下のメソッドが追加される。 2021-12-22 22:19:48
AWS AWSタグが付けられた新着投稿 - Qiita Raspberry PiとAWS IoT Eventsを連携させてデバイスの状態エラーをメール通知する https://qiita.com/dsonoda/items/b2e6557f9bfa29ecee14 「ステータス」とスイッチの状態、クラウド送信値の関係は以下となる。 2021-12-22 22:54:51
Docker dockerタグが付けられた新着投稿 - Qiita Docker コンテナで特定のコマンドしか実行できないユーザーを作成したい https://qiita.com/blueskyarea/items/4e3c8888f4358b6fde64 コンテナからイメージ作成dockercommitcontaineridawkbase作成したイメージを元に、制限したいユーザーawkerでbash起動するdockerrunuawkeritawkbasebashシェルをrbashに変更するchshChangingshellforawkerNewshellbinbashbinrbashPasswordユーザ作成時に設定したパスワードShellchangedbashprofileの所有者・グループをrootにするawker自身では変更できないようにするため。 2021-12-22 22:20:18
golang Goタグが付けられた新着投稿 - Qiita カジュアルゲームをEbitenで作る https://qiita.com/ichiban_kunio/items/cff6cf3bbdd12856ff9b golangpictwittercomKGOdJlPePーIchibanKuniokuDecember作るEbitenは最低限のAPIを持つので、APIをラップするような形で自分好みに便利な関数を作っていくのが楽しいです。 2021-12-22 22:35:33
Ruby Railsタグが付けられた新着投稿 - Qiita 他業種からプログラミング講座に挑戦してみて見えたこと(課題) https://qiita.com/chi71/items/5d2cd101b74c0ed49d92 乗り越えたと思って実はできていなかったこと見えていなかった部分・調べることで、その場で解決して変な自信や満足感を得ているが、根本的に理解できていない。 2021-12-22 22:40:44
Ruby Railsタグが付けられた新着投稿 - Qiita has_one関連付けのbuild_associationメソッドは暗黙的にレコードを削除する https://qiita.com/evitch/items/7a3204e540112811b3e3 hasone関連付けのbuildassociationメソッドは暗黙的にレコードを削除する環境RailsRubyMySQL前提userrbclassUserltApplicationRecordhasoneitemdependentdestroyenditemrbclassItemltApplicationRecordbelongstouserend解説ActiveRecordでhasone関連付けを利用すると、以下のメソッドが追加される。 2021-12-22 22:19:48
技術ブログ Developers.IO いわささん、『四半期毎日投稿(&毎日投稿継続中)』の快挙達成の経緯について聞かせてください。 – DevelopersIO ブロガー達に色々聞いてみた Advent Calendar 2021 https://dev.classmethod.jp/articles/interviews-with-classmethod-developersio-bloggers-day22-iwasa/ adventcalend 2021-12-22 13:51:52
海外TECH MakeUseOf 11 Useful HTML Attributes You Must Know https://www.makeuseof.com/useful-html-attributes-to-know/ useful 2021-12-22 13:45:12
海外TECH MakeUseOf How to Write a Project Proposal https://www.makeuseof.com/how-to-write-a-project-proposal/ proposal 2021-12-22 13:30:12
海外TECH MakeUseOf The 6 Best Remote-Controlled Heaters https://www.makeuseof.com/best-remote-controlled-heaters/ control 2021-12-22 13:00:35
海外TECH DEV Community Must have cheat sheet for WEB DEVELOPER https://dev.to/officialkamran/must-have-cheat-sheet-for-web-developer-3kcd Must have cheat sheet for WEB DEVELOPERHTML CHEAT SHEETI love them as they offer me a simple way to recall a software program or help me to learn a new skill Plus there s always a useful keyboard shortcut to forget a command you will just fail to remember a newly introduced function that slips your mind or element you cease to think of CSS CHEAT SHEETat this website we present a printable CSS Cheat Sheet a complete listing of all the properties selectors types and allowed values in the current CSS specification from the WC Each property is provided in a section that attempts to match it with the section module that it is most actively associated within the WC specification JAVASCRIPT CHEAT SHEET HERE YOU CAN FIND THE JAVASCRIPT CHEAT SHEET IN pdf AS WELL AS IN THE TEXT Everything on one place download a print able PDF JQUERY CHEAT SHEETEnjoy an interactive list of Bootstrap classes Chose to copy Code snippet of CSS class BOOTSTRAP CHEAT SHEET 2021-12-22 13:44:01
海外TECH DEV Community Spans - a key concept of distributed tracing 📊 https://dev.to/signoz/spans-a-key-concept-of-distributed-tracing-4idg Spans a key concept of distributed tracing Spans are fundamental building blocks of distributed tracing A single trace in distributed tracing consists of a series of tagged time intervals known as spans Spans represent a logical unit of work in completing a user request or transaction Distributed tracing is critical to application performance monitoring in microservice based architecture Before we deep dive into spans let s have a brief overview of distributed tracing What is distributed tracing In a microservices architecture a user request travels through hundreds even thousands of services before serving the user what they need Engineering teams often responsible for maintaining single services have no visibility over how the system performs as a whole Microservice architecture of a fictional e commerce applicationDistributed tracing gives insights into how a particular service is performing as part of the whole in a distributed software system It involves passing a trace context with each user request which is then passed across hosts services and protocols to track the user request These requests are broken down into spans and the entire request is represented by a trace What are spans in distributed tracing In distributed tracing a user request or a transaction is represented by a trace Traces are broken down into multiple spans Spans represent a single logical operation within a trace For example a function call during a user request can be represented by a span Spans in distributed tracing What are spans Each unit of work in a trace is represented by a span A trace represents a complete process for a request from its initiation to its completion The picture below shows one trace which is composed of multiple spans A complete trace consisting of multiple spans shown on SigNoz dashboardThe first span is known as the parent span and the subsequent spans are child spans Parent Span Also known as root spans a parent span encapsulates the end to end latency of an entire request To explain it more clearly let us define adding a product to a cart on an e commerce website as a user request The parent span will measure the time it took from the event of an end user clicking a button to the product being added to the cart The parent span can also end if some error occurs Child Spans A child span is triggered by a parent span and can be a function call DB calls calls to another service etc In the example mentioned above a child span can be a function checking whether the item is available or not Child spans provide visibility into each component of a request Combining all the spans in a trace can give you a detailed idea about how the request performed across its entire lifecycle What are spans composed of A span contains a span context that uniquely identifies the request the span is part of Spans can provide request error and duration metrics that can be used to debug availability and performance issues You can also add span attributes to provide more context to your operations Span attributes are key value pairs that can be used to provide additional context on a span about the specific operation it tracks Let us see details of a selected span in an APM tool like SigNoz Span attributes Details associated with a span captured by SigNoz Example of a basic spanLet s see an example of creating a basic span using the OpenTelemetry instrumentation library OpenTelemetry is a set of API SDKs libraries and integrations that is aiming to standardize the generation collection and management of telemetry data logs metrics and traces Example of creating a basic span in java Source OpenTelemetry docs Span span tracer spanBuilder my span startSpan put the span into the current Contexttry Scope scope span makeCurrent your use case catch Throwable t span setStatus StatusCode ERROR Change it to your error message finally span end closing the scope does not end the span this has to be done manually Example of adding span attributesSpan span tracer spanBuilder resource path setSpanKind SpanKind CLIENT startSpan span setAttribute http method GET span setAttribute http url url toString Read more about OpenTelemetry OpenTelemetry Collector architecture and configuration guide 2021-12-22 13:26:38
海外TECH DEV Community Docker for Javascript Developers https://dev.to/alexeagleson/docker-for-javascript-developers-41me Docker for Javascript DevelopersAll code from this tutorial as a complete package is available in this repository For more tutorials like this follow me eagleson alex on Twitter Table of ContentsIntroductionWhat is Docker PrerequisitesInstalling DockerCreating a ContainerCreating a Node AppDeprecating the Node AppCreating a DockerfileDocker Layers and CacheAdding a Docker VolumeWhat is Docker Compose Adding a DatabaseConnecting the App to the DatabaseAdding a FrontendCreating a Docker Compose YML FileAdding a pgAdmin Panel Bonus Wrapping Up IntroductionIn this tutorial you will learn what Docker is and what purpose it serves by building a fullstack Node js app complete with frontend and PostgreSQL database We will use Docker Compose to connect and network each container together so that they are easy to share among project contributors and deploy to whatever hosting service you ve chosen What is Docker Docker is a tool that allows you package the environment for running your application along with the application itself You can accomplish this as simply as including a single file called Dockerfile with your project It uses a concept it calls containers which are lighter weight require less resources than full on virtual machines to create the environment for your application These containers are designed to be extremely portable which means that you can quickly deploy them anywhere and also scale up your app quickly by simply deploying more copies of your container All you need to do is define the requirements for your environment in the Dockerfile for example Ubuntu Node js etc and every time your container is started on any machine it will recreate exactly that environment So you already know in advance that you will not have any issue with missing dependencies or incorrect versions That said it can be challenging to really demonstrate the need for Docker to those new to the development world who haven t yet experienced a lot of the problems that it solves This tutorial aims to simulate a a couple of realistic scenarios you might encounter in a work environment and show how Docker helps to solve those issues The ScenarioThere are two common development issues we will be replicating with this example Your company s project relies on an older version of a tool in our case Node js than the development team has installed on their machineWe want to make it easy to test the application with a copy of the database on the developers local machine without requiring them to install the database software in our case PostgreSQL If you follow this tutorial you will have a working application running on your machine and querying a Postgres DB without the need to have either Node js or Postgres installed The only tool you will need is Docker scalability PrerequisitesThe only prerequisite software required to have installed for this tutorial is an IDE code editor I use VS Code and Docker How you install Docker will depend on the operating system you are running I am running it on WSL on Windows which is a fantastic experience It works just as well on Mac and Linux you simply need to follow the installation instructions for your OS I recommend Docker Desktop which will give you a nice GUI for working with Docker however it is not required For this tutorial will will be managing Docker entirely through the command line though I may use Docker Desktop for screenshots to show what is happening I also suggest having Node js installed as well Technically you can get away without it but in the first couple of steps we re going to run the app locally before we get Docker involved It will also help demonstrate how Docker fixes our versioning issue Installing DockerOnce you have Docker installed let s make sure that it works When you type docker versionYou should get a version number as opposed to not found My version right now shows but any version close to that number should work fine Most containers are hosted on a service called Docker Hub including the ones we will be using Let s begin by testing the simplest container called hello world Creating a ContainerRun the following command to download the hello world image docker pull hello worldThat will pull the image from Docker hub Important to get the terminology correct we haven t created a container yet A Docker image is a set of instructions for how to create a container If you are familiar with web development think of the image like HTML blueprints and the container like the DOM the structure You can add additional instructions to the default image instructions in your Dockerfile which we will get to soon Presuming you got a success message like Status Image is up to date for hello world latest you are ready to create a container docker run hello worldIf successful you will see this output in your terminal Hello from Docker This message shows that your installation appears to be working correctly To generate this message Docker took the following steps The Docker client contacted the Docker daemon The Docker daemon pulled the hello world image from the Docker Hub amd The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading The Docker daemon streamed that output to the Docker client which sent it to your terminal To try something more ambitious you can run an Ubuntu container with docker run it ubuntu bashShare images automate workflows and more with a free Docker ID For more examples and ideas visit Congratulations You have run your first Docker container Although you can manage it very easily if you are using Docker Desktop let s look at a couple of the most common commands to manage it on the command line docker image lsdocker container lsWill show you a list of all the images or containers you have on your system at the moment Because hello world stops as soon as it s finished printing the test message it does not keep running forever like a container running a web app would You won t see it in your list of containers but you will see it in your list of images Both the ID of the image container and the name are important to be able to lookup because they allow you to refer to those images containers to start stop them When you stop running a container it doesn t get deleted That is a good thing It means it s super fast to just start it up again the next time you need it without downloading and installing it again While working with Docker you ll find that sometimes these images and containers begin to pile up when you change things or build new versions To quickly remove all old unused ones you can run docker image prunedocker container pruneIf these don t seem too helpful now don t worry but keep them in mind because you will likely want to refer back to them later Creating a Node AppBefore we get any further into Docker let s build a small web app we can use to help demonstrate some of the more advanced features of Docker We re going to build a simple web server in Node js and Express I ve created a new empty directory called docker template and initialized an NPM repo inside of it mkdir docker templatecd docker templatenpm initnpm install expressserver jsconst express require express const app express const port app get async req res gt res setHeader Content Type text html res status res send lt h gt Hello world lt h gt app listen port gt console log Example app listening at http localhost port Now run your app with node server jsAnd go to http localhost to see One extra thing we would like to enable for this project is file watching and automatic reloading of the server whenever the file is changed The easiest way to do that is a tool called nodemon npm install nodemon save devThen add a start script to your package json file package json name server version description main server js scripts start nodemon server js author me license ISC dependencies express devDependencies nodemon Run your app with npm run startTry editing your server js file when your app is running change hello world to hello world or something and verify that your Node app reloads and you see the change in your browser when you hit the refresh button the file watching won t trigger a browser refresh automatically Once that is working continue to the next step Deprecating the Node AppThis next part is kinda fun Let s intentionally turn this server into a legacy project We ll be assuming you are running a recent version of Node or later You can check by running node versionMy output is v If yours is older than you can either use NVM or just read along Installing a specific Node version of your machine is not required for this part In fact it s exactly the problem we re going to solve with Docker in the next section In Node there is a breaking change in the way that unhandled rejected promises are handled Before version a Javascript promise that was rejected without a catch would give a warning and keep running but after v of Node an unhandled promise will crash the program So it s possible for use to add some code that will make our server work on versions of Node older than but not work on new versions of Node Let s do that now server js ts checkconst express require express const app express const port app get async req res gt res setHeader Content Type text html res status res send lt h gt Hello world lt h gt app listen port gt console log Example app listening at http localhost port const myPromise new Promise resolve reject gt setTimeout gt resolve good reject bad myPromise then gt console log this will never run The code above creates a new promise that always rejects It will run with a warning on Node js v but will crash on v and above Try running it yourself on v and above and you get code ERR UNHANDLED REJECTION Now obviously we could just add a catch block or remove the code entirely but we are trying to replicate a scenario where you are working with an older codebase and you may not necessarily have those options available to you Let s say for one reason or another this app must be run on Node v to work Every developer on the team must be prepared to operate in that environment but our company also has a new app that runs on Node v So we need that environment available too And while we re at it some other tool on version X I only have version Y on my machine Who knows what version the other members of my team are running Or the guy I send the app to for testing What do I do Enter Docker Creating a DockerfileWith Docker we can use code to generate the environment that our app runs in We ll begin by searching Docker hub for a Node js image The official Node image is just called node You ll notice when you look at supported tags there are a lot of versions Just like having a certain version on your machine there s Docker images for pretty much every version you could want Of course Node itself needs to be installed on some kind of operating system so that s usually the other part of the tag The default Node image runs on Debian however one of the most popular versions runs on something called Alpine Linux The main reason Alpine is popular is because of its small size it s a distro of Linux designed to strip out all but the most necessary parts This means it will be faster and more cost effective to run and distribute our app on this image assuming it meets our needs For our simple app it does Remember we specifically want an older version of Node older than v so our app runs without crashing so I am going to choose the image tagged node alpine That s Node v and Alpine v We can pull the image in advance with docker pull node alpine just like we did with hello world but it s not necessary By adding it to our Dockerfile Docker will automatically pull it from Docker Hub if it doesn t find it on our machine Let s create a file called Dockerfile no extension in the root of our project next to server js Dockerfile select your base image to start withFROM node alpine Create app directory this is the location where you will be inside the containerWORKDIR usr src app Install app dependencies A wildcard is used to ensure both package json AND package lock json are copied where available npm copying packages first helps take advantage of docker layersCOPY package json RUN npm install If you are building your code for production RUN npm ci only production Bundle app sourceCOPY Make this port accessible from outside the container Necessary for your browser to send HTTP requests to your Node appEXPOSE Command to run when the container is ready Separate arguments as separate values in the arrayCMD npm run start I ve added a lot of comments to help explain each piece of the Dockerfile You can learn more about Dockerfiles here I would highly encourage you to skim through that page to get familiar with the commands that are available Before we continue I would like to touch briefly on Docker s layers amp cache because they are very important topics Docker Layers and CacheOne common question for a simple Dockerfile like this is Why are you using the COPY command twice Isn t the first COPY unnecessary since the second one copies the whole directory The answer is actually no and the reason is because of one of Docker s best features called layers Every time you use one of FROM COPY RUN CMD it creates another image which is based off the previous layer That image can be cached and only needs to be created again if something changes So by creating a specific COPY line on package json we are creating a layer that is based off the content of that file before we run npm install That means that unless we change package json the next time we build Docker will use the cache layer where npm install has already been run and we don t have to install all dependencies every time we run docker build That will save us an enormous amount of time The next COPY looks at every file in our project directory so that layer will be rebuilt on any file change basically any time we update anything OTHER than package json in our app But that s exactly what we want This is just one example of efficiencies you can take advantage of when working with Docker but I would encourage you to read the whole list of best practices for Dockerfiles Building the App ContainerNow that your Dockerfile is created we have just one last thing we need to do before we build Similar to gitignore that you re probably familiar with used to prevent committing auto generated files and private secrets to public repositories Docker has a similar concept to keep you from unnecessarily copying files that your container doesn t need Let s create a dockerignore file now dockerignorenode modulesnpm debug logBoth of those will be generated inside the container so we don t want to copy our local versions of them over At this point we are ready to build Run the following command docker build t my node appThat will build the image describe by the Dockerfile in the current directory and give it a name called my node app When it s done you can see the image and all its details with docker image lsWith the image created we are now ready to build a container off our image which will run our app docker run p name my node app container my node appThis command tells Docker to use our image to build a running container The name flag lets us name the container to make it easier to identify and stop start later otherwise the name will be randomly generated I used the name my node app container to differentiate it from the last argument which is the name of the image we are building from my node app We use the p flag to bind ports from our host machine our computer environment to the container environment If you recall we wrote EXPOSE in our Dockerfile which is the port our app runs on The above command maps port on our machine to port in the container Note you can map the same port like if you like we just mixed it up in this example to show that it s possible Double check that your container started successfully with docker container lsMy output looks like CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESbbe my node app docker entrypoint s… minutes ago Up minutes gt tcp my node app container Sorry if the words wrap and it make it difficult to line things up We can see that the container is up for X minutes That means that our app is running on port we can access that port on our machine using port so open up your browser to http localhost to see Great You ve created your first custom Docker image and container with your own app running in it So now that you have your environment setup naturally one of the next things you might want to do is update your app If you make a change to server js and save the file are you going to see those changes when you reload the page No you won t The app is running based on a copy of server js inside the container which has no direct relation to the one in your project directory Is there a way that we can connect them somehow Of course there is we need to introduce Docker volumes Adding a Docker VolumeDocker uses the concept of volumes to allow you to persist data between running containers You can imagine you might want to have your app save some data but with the way Docker works your containers are designed to be destroyed and recreated casually There are two primary ways to use volumes You can create one in advance and give it a name This will save all the volume data by default in the var lib docker volumes directory in a Linux environment it would be somewhere different but equivalent on Windows To create a named volume you don t need to run this command for this tutorial it s simply an example docker volume create my named volumeThen you would map any directory in your container to that directory on your machine You can do so by adding the volume flag to your docker run command like so volume my named volume usr src app my node app That example would map the working directory in your container to the Docker volume on your machine This does not help us however because we want to synchronize a specific directory our project directory with the one in the container so we can edit files in our project and have them update in the container We can do this as well First we need to stop the existing container which doesn t have a volume remove it and then run it again with the volume docker container stop my node app containerdocker container rm my node app containerdocker run p name my node app container volume PWD usr src app my node appIn most terminals PWD means print working directory so it will map the current directory to the usr src app directory inside your container This will accomplish our goal of syncing the files between our project on our computer and the one in our container Since we have already set up file watching and reloading with nodemon earlier in the tutorial you should now be able to edit server js in your project directory while the container is running just edit the hello world text then refresh your browser to see the changes And that s it You now have a Dockerized Node app where you can make changes on your machine and see the updates happen live inside your container At this point we have mostly completed our introduction to Docker itself We have completed our implementation of our first scenario where we use coded instructions to recreate the environment that our app requires in order to operate We now need to address our second common scenario in order to function our application relies on other services like a database for example We could technically add the instruction to install the database in our Dockerfile but that would not realistically mimic the environment our app would be deployed in It s not guaranteed that our Node app and our database would be hosted on the same server In fact it s probably not even likely Not only that we don t want to have to boot up our web server to make edits to our database and vice versa Is there a way that we can still use Docker but create a separation between multiple services that rely on each other Yes we can What is Docker Compose Best described in their own words Compose is a tool for defining and running multi container Docker applications With Compose you use a YAML file to configure your application s services Then with a single command you create and start all the services from your configuration The process is to define the instructions for each of your services with Dockerfiles and then use Docker Compose to run all those containers together and facilitate network communications between them In this tutorial we are going to connect our Node app to a PostgreSQL database Before we can connect them of course we need to establish the database container Adding a DatabaseSimilar to Node Docker Hub has a super simple easy to use image for PostgreSQL Of course theres also images for MySQL Mongo Redis etc etc There s no reason you couldn t substitute your favourite out if you want though if you re still new to Docker I d suggest you stick with the tutorial for now We search Docker Hub for the official postgres image We don t need anything beyond the bare minimum so once again we ll choose the version running on Alpine Image postgres alpine Unlike our Node image we don t need to copy any files or run any installation scripts so we don t actually need a Dockerfile for our PostgreSQL installation There are some configurations that we do need like password and ports for example but we can manage those with our upcoming docker compose yml file So aside from deciding which image you are going to use there is really nothing else we need to do before we create our config file Connecting the App to the DatabaseBefore we create the Docker Compose configure file to link the database container we need to update our app to actually use it Our goal here is going to be to create a database with some very simple data like a list of employees see it with some sample data and then query that data with our Node app We ll also create a simple frontend to display that data First we need to install the PostgresSQL NPM package npm install pgNext we are going to create a sql file that will automatically seed out database with some sample data to read from In the root of the project create the following file database seed sqlCREATE TABLE employees id SERIAL name text title text CONSTRAINT employees pkey PRIMARY KEY id INSERT INTO employees name title VALUES Meadow Crystalfreak Head of Operations Buddy Ray Perceptor DevRel Prince Flitterbell Marketing Guru Note I got those ridiculous names from the random name generator on the whimsical setting Next we update our Node server to query these values In addition to doing that we are going to use express static to serve up an entire directory rather than just sending HTML as sa string This will allow us to serve an HTML file along with some CSS and Javascript as well to create a full fledged frontend Comments are added to explain all the new pieces server js Import the postgres clientconst Client require pg const express require express const app express const port Connect to our postgres database These values like root and postgres will be defined in our docker compose yml fileconst client new Client password root user root host postgres Serves a folder called public that we will createapp use express static public When a GET request is made to employees Our app will return an array with a list of all employees including name and title this data is defined in our database seed sql fileapp get employees async req res gt const results await client query SELECT FROM employees then payload gt return payload rows catch gt throw new Error Query failed res setHeader Content Type application json res status res send JSON stringify results Our app must connect to the database before it starts so we wrap this in an IIFE Google it so that we can wait asynchronously for the database connection to establish before listening async gt await client connect app listen port gt console log Example app listening at http localhost port const myPromise new Promise resolve reject gt setTimeout gt resolve foo reject oops myPromise then gt console log hello In the above code update you can see that we are serving up a directory called public that we have not created yet That directory will contain an index html file to act as the nice looking frontend for our app Adding a FrontendWe ll begin by creating the public directory that is being served from our Node app mkdir publicThen add the following files public index html lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta name viewport content width device width initial scale gt lt title gt My Docker Template lt title gt lt script src script js gt lt script gt lt link rel stylesheet href styles css gt lt head gt lt body gt lt template gt lt div class card gt lt img src alt Avatar width px gt lt div class container gt lt h gt Placeholder lt h gt lt p gt Placeholder lt p gt lt div gt lt div gt lt template gt lt body gt lt html gt Our index html file takes advantage of HTML templates for the employee cards public styles cssbody padding px display flex flex direction row column gap px card box shadow px px rgba transition s border radius px transition s card hover transform scale container padding px img border radius px px Above in styles css is some simple CSS to give a clean look to the employee card templates and flex them out in a row across the page public script jsfetch employees then response gt response json then data gt console log data data forEach employee gt const cardTemplate document querySelector template const card cardTemplate content cloneNode true card querySelector h innerText employee name card querySelector p innerText employee title document body appendChild card When our app is loaded it will load script js which will use the browser fetch API to query the employees route on our Node server and get the employee information from out PostgreSQL database Once it is returned it will iterate through each employee and clone the HTML template that we defined in index html to make a custom employee card with that employee s name and title Phew Now that we have our app established and ready to read from the database we are finally ready to connect our Node container and our PostgreSQL container together with Docker Compose Creating a Docker Compose YML FileFor a brief intro to compose see here and for more details than you can ever handle about the compose file spec see here We re going to be creating a simple docker compose yml file to link our Node app with our PostgreSQL database Let s jump right in and create the file in our project root directory I ll use lots of comments to explain everything docker compose ymlversion services These are the configurations for our Node app When Docker Compose starts this container it will automatically use the Dockerfile in the directory to configure it app build depends on Our app does not work without our database so this ensures our database is loaded first postgres ports volumes Maps our current project directory to our working directory in the container usr src app This is the configuration for our PostgreSQL database container Note the postgres name is important in out Node app when we refer to host postgres that value is mapped on the network to the address of this container postgres image postgres alpine restart always environment You can set the value of environment variables in your docker compose yml file Our Node app will use these to connect to the database POSTGRES USER root POSTGRES PASSWORD root POSTGRES DB root ports Standard port for PostgreSQL databases volumes When the PostgresSQL container is started it will run any scripts provided in the docker entrypoint initdb d directory this connects our seed file to that directory so that it gets run database seed sql docker entrypoint initdb d database seed sqlSo with that docker compose yml file in place we are finally ready to run our new and highly improved application suite that includes a backend frontend and database From the root directory of the project all your have to do is type docker compose up build Note the build flag is used to force Docker to rebuild the images when you run docker compose up to make sure you capture any new changes If you simply want to restart existing containers that haven t changed you can omit it Once active you can finally test it out In our docker compose yml config we are mapping post directly to so go to http localhost to see With a cute little hover transition and everything Congratulations If you are using the Docker Desktop GUI application you ll have a lot of options to stop all the containers at once or view each one individually If you are using the command line you can stop both containers with this simple command run from the project root directory for context docker compose downAnd there you have it a fullstack Node js application with its own SQL database bundled along with it You can now deploy this literally anywhere that has Docker installed and you know that it will work because you have defined all the parameters of the exact environment it needs to function Adding a pgAdmin Panel Bonus Here s a quick little bonus for those of you who are using PostgreSQL Adding the pgAdmin panel container to this app setup is a breeze SImply update your docker compose yml config to include the following docker compose ymlversion services app build depends on Our app does not work without our database so this ensures our database is loaded first postgres ports volumes Maps our current project directory to our working directory in the container usr src app This is the configuration for our PostgreSQL database container Note the postgres name is important in out Node app when we refer to host postgres that value is mapped on the network to the address of this container postgres image postgres alpine restart always environment You can set the value of environment variables in your docker compose yml file Our Node app will use these to connect to the database POSTGRES USER root POSTGRES PASSWORD root POSTGRES DB root ports Standard port for PostgreSQL databases volumes When the PostgresSQL container is started it will run any scripts provided in the docker entrypoint initdb d directory this connects our seed file to that directory so that it gets run database seed sql docker entrypoint initdb d database seed sql pgadmin compose image dpage pgadmin environment PGADMIN DEFAULT EMAIL placeholder example com PGADMIN DEFAULT PASSWORD fakepassword ports depends on postgresNotice the pgAdmin panel configuration added at the bottom When you run docker compose up build now and go to http localhost You ll be greeted with the pgAdmin panel Enter the PGADMIN DEFAULT EMAIL and PGADMIN DEFAULT PASSWORD credentials from the docker compose yml file to access it Once inside click Add New Server For General gt Name pick a name Can be whatever you want On the Connection tab values must match the docker compose yml file Host postgresUsername rootPassword rootNow you can navigate from the left bar Servers gt whatever you want gt Databases gt root gt Schemas gt public gt Tables gt employeesRight click employees an Query Tool SELECT FROM employees To see your data Wrapping UpI hope you learned a lot about why Docker is a fantastic tool in your toolbelt and how you can use it to reduce the amount of friction related to setting up development environments The days of fighting with WAMP and MAMP and XAMPP are thankfully long behind us no slight against those apps I know they re fantastic tools when configured properly Remember that Docker can be used both to create a baseline standard development environment on the machines of many different developers But it s not just a development tool Docker can be used in production as well to simplify the process fo scaling your app up with increased traffic by simply deploying more containers And there s plenty more to learn well beyond what s covered here the Docker docs are the best place to start All the best in your Docker journey Please check some of my other learning tutorials Feel free to leave a comment or question and share with others if you find any of them helpful Learnings from React Conf How to Create a Dark Mode Component in ReactHow to Analyze and Improve your Create React App Production Build How to Create and Publish a React Component LibraryHow to use IndexedDB to Store Local Data for your Web App Running a Local Web ServerESLintPrettierBabelReact amp JSXWebpack The BasicsWebpack Loaders Optimizations amp Bundle Analysis 2021-12-22 13:24:29
海外TECH DEV Community AatroX Vue Lite - Open-Source VueJS 3 & TailwindCSS Admin Dashboard Template is Out Now! https://dev.to/uilibofficial/aatrox-vue-lite-open-source-vuejs-3-tailwindcss-admin-dashboard-template-is-out-now-5h30 AatroX Vue Lite Open Source VueJS amp TailwindCSS Admin Dashboard Template is Out Now AatroX Vue Lite Open Source VueJS amp TailwindCSS Admin Dashboard Template is a useful developer friendly and highly customizable dashboard template It has everything you could want in an admin dashboard We adhered to the highest industry standards to provide you with the best Vue Admin template Atrox is extremely fast and simple to use as well as highly scalable So with a little effort you will be able to create any application you desire Furthermore the template design is eye catching and fully responsive As a result no matter what device they use anyone who visits your application will have a fantastic experience It will run smoothly on all devices including desktops tablets and smartphones With the help of this template you can create web apps like Ecommerce BackendsAnalytics AppsSaaS PlatformsProject Management AppsEducation AppsFitness Appsand a lot more Atrox also includes useful features that will help you create high quality apps exactly as you envision them Furthermore we ve loaded the Atrox admin template with useful features like Vitejs Nuxt inspired routing accessible front end routing and so on Key FeaturesVue amp ViteBeautifully CraftedtailwindCSSNuxt inspired RoutingWell OrganizedProduction ReadyAccessible frontend routingReady to DeployClean Code Installation ️We recommend you use yarn Install all packagesyarn npm install for npm Run development serveryarn dev npm run dev for npm Generate build files for deploymentyarn build npm run build for npm What s Included Dashboard PageButtons PageProfile PageSign in PageSign Up Page Browser Support ️AatroX Vue Lite open source VueJS amp TailwindCSS admin dashboard template is built to work best in the latest desktop and mobile and tablet browsers It supports all the major browsers including Chrome latest FireFox latest Safari latest Opera latest DocumentationDocumentation Looking For a Premium Version If you want to save even more time and design effort we have a pro version of this product that includes even more pages and components You can upgrade to the Aatrox Vue Vuejs amp TailwindCss Admin Dashboard s version It comes with many dashboard versions apps tons of components charts and a lot more Free Version Aatrox Dashboard PRO Demo Pages  demo pagesDark amp Light Mode Dashboard Dashboard App Pages UiKits Pages Advanced Widgets Profile Version Profile Versions Authentication Page Authentication Pages Types of Charts Demo PagesFor more info click the image below About UsWe are Ui Lib a team of awesome developers and designers attempting to make the lives of other developers easier 2021-12-22 13:14:56
海外TECH DEV Community Welcome Thread - v156 https://dev.to/thepracticaldev/welcome-thread-v156-436f Welcome Thread v Welcome to DEV Leave a comment below to introduce yourself You can talk about what brought you here what you re learning or just a fun fact about yourself Reply to someone s comment either with a question or just a hello Great to have you in the community 2021-12-22 13:05:56
Apple AppleInsider - Frontpage News New Apple iCloud Private Relay guide details what it doesn't cover https://appleinsider.com/articles/21/12/22/new-apple-icloud-private-relay-guide-details-what-it-doesnt-cover?utm_medium=rss New Apple iCloud Private Relay guide details what it doesn x t coverApple s new iCloud Private Relay privacy feature remains in beta on iOS but the company has now published a primer about how it works how to use it ーand what it won t do Apple s iCloud Private Relay remains in betaOriginally announced as part of iOS the feature has instead been in public beta and problems have been found Now Apple has published the iCloud Private Relay Overview which describes how the feature protects users privacy on the internet Read more 2021-12-22 13:23:55
Apple AppleInsider - Frontpage News Vintage iPod Shuffle as hair clip video goes viral, makes us all feel old https://appleinsider.com/articles/21/12/22/vintage-ipod-shuffle-as-hair-clip-video-goes-viral-makes-us-all-feel-old?utm_medium=rss Vintage iPod Shuffle as hair clip video goes viral makes us all feel oldIn a clip that makes the AppleInsider staff feel old a new TikTok clip shows a user asking what this vintage device she s found is ーand discovering a new use for what turns out to be an iPod shuffle Apple s old iPod shuffle with a new iPhoneAccording to Newsweek more than two million people have watched Celeste Tice freckenbats on TikTok examine the device like she s on the Antiques Roadshow Read more 2021-12-22 13:21:09
Apple AppleInsider - Frontpage News Shareholders doubt Apple's civil rights stance, call for investigation https://appleinsider.com/articles/21/12/22/shareholders-doubt-apples-civil-rights-stance-call-for-investigation?utm_medium=rss Shareholders doubt Apple x s civil rights stance call for investigationA group of Apple shareholders are requesting a civil rights audit saying the company s actions against staff goes against its stated mission and values Apple CEO Tim CookThe US SEC has allowed a shareholder proposal concerning Apple s alleged use of concealment clauses and non disclosure agreements but now a separate group wants more Read more 2021-12-22 13:08:16
Apple AppleInsider - Frontpage News New & colorful 27-inch iMac starts production, reportedly won't have mini LED https://appleinsider.com/articles/21/12/22/new-colorful-27-inch-imac-starts-production-reportedly-wont-have-mini-led?utm_medium=rss New amp colorful inch iMac starts production reportedly won x t have mini LEDA new report says that suppliers have begun producing Apple s updated inch iMac and that it will not feature a mini LED screen ーbut will come in many colors The new inch iMac is said to feature the same or similar thin design as the inch modelPrevious reports have claimed that mini LED will be used in the inch iMac ーor possibly a separate iMac Pro ーreleasing in early Now unspecified sources in the supply chain have told Digitimes that the iMac won t have this newer screen technology Read more 2021-12-22 13:42:10
海外TECH Engadget NASA delays James Webb telescope launch due to poor weather https://www.engadget.com/nasa-delays-james-webb-telescope-launch-poor-weather-132056161.html?src=rss NASA delays James Webb telescope launch due to poor weatherThe James Webb Space Telescope is finally ready for launch after years in development NASA cleared its launch readiness review and gave it the go ahead for launch which was supposed to take place on December th Unfortunately poor weather conditions have prompted the agency to delay its launch yet again James Webb will be lifting off from Europe s Spaceport in French Guiana on an Arianespace Ariane rocket with the new target date of December th and a launch window of between AM and AM Eastern time This is the closest the telescope has ever gotten to starting its month long journey towards its destination It s been delayed numerous times in the past due to one reason or another ーNASA targeted an October launch date after its development was delayed by the pandemic but it determined that the telescope wouldn t be ready until November or December nbsp NASA and its partners the European and Canadian space agencies then targeted a December th launch date before pushing it back to December nd The James Webb team needed the extra time to inspect the telescope and make sure nothing was damaged during an incident that happened at testing Its launch was delayed to December th after that because of a communication issue between the telescope and its Ariane launch vehicle This time NASA had already conducted a news conference confirming that the telescope is ready for launch before announcing the new target date After the James Webb telescope arrives in its orbit near the second Lagrange point of the Earth Sun system researchers around the world will be able to use it to peer at some of the universe s earliest galaxies look into black holes and assess exoplanets habitability NASA will confirm the new launch date this evening Due to adverse weather conditions at Europe s Spaceport in French Guiana the James Webb Space Telescope s launch is postponed from Dec to no earlier than Dec A weather forecast will be issued tomorrow to confirm this date UnfoldTheUniversepic twitter com cvUKZuLーNASA Webb Telescope NASAWebb December 2021-12-22 13:20:56
海外TECH CodeProject Latest Articles Converting Camel Case Names to Human Case Labels https://www.codeproject.com/Tips/5320583/Converting-Camel-Case-Names-to-Human-Case-Labels object 2021-12-22 13:18:00
海外科学 NYT > Science In a Boston Court, a Superstar of Science Falls to Earth https://www.nytimes.com/2021/12/21/science/charles-lieber.html In a Boston Court a Superstar of Science Falls to EarthA jury found the Harvard chemist Charles Lieber guilty of lying to the federal government about his participation in China s Thousand Talents recruitment program 2021-12-22 13:05:27
ニュース BBC News - Home Covid in Wales: Groups of six allowed to meet in pubs https://www.bbc.co.uk/news/uk-wales-59752752?at_medium=RSS&at_campaign=KARANGA restaurants 2021-12-22 13:35:49
ニュース BBC News - Home Covid: Self-isolation cut from 10 days to seven with negative tests https://www.bbc.co.uk/news/uk-politics-59749447?at_medium=RSS&at_campaign=KARANGA christmas 2021-12-22 13:31:44
ニュース BBC News - Home Salford snake: Forklift driver finds deadly reptile in brickyard https://www.bbc.co.uk/news/uk-england-manchester-59757342?at_medium=RSS&at_campaign=KARANGA pakistan 2021-12-22 13:42:39
ニュース BBC News - Home Covid: What are the social distancing rules this Christmas? https://www.bbc.co.uk/news/uk-51506729?at_medium=RSS&at_campaign=KARANGA christmas 2021-12-22 13:53:11
ニュース BBC News - Home Omicron: What are the new Covid rules for the UK? https://www.bbc.co.uk/news/explainers-52530518?at_medium=RSS&at_campaign=KARANGA omicron 2021-12-22 13:23:22
ビジネス ダイヤモンド・オンライン - 新着記事 オイレス工業、株主優待の変更と「記念配当」を発表! 「プレミアム優待倶楽部」をもらうために必要な最低 株数が「100株⇒300株」に引き上げられることに! - 株主優待【新設・変更・廃止】最新ニュース https://diamond.jp/articles/-/291700 オイレス工業の株主優待は、毎年月末時点の株主に実施されており、従来の内容は「株以上の株主に、保有株数と保有期間に応じて『プレミアム優待倶楽部』のポイントを贈呈」というものだった。 2021-12-22 22:50:00
LifeHuck ライフハッカー[日本版] 地球にもお財布にも優しい「電子メモパッド」が大活躍|これ買ってよかった2021 https://www.lifehacker.jp/2021/12/248018digital-memo-pad.html 電子 2021-12-22 22:05:00
北海道 北海道新聞 雪まつり 大通公園に中・小雪像10基 日ハム新球場や雪ミク コロナ対策で一方通行、物販なし https://www.hokkaido-np.co.jp/article/626322/ 一方通行 2021-12-22 22:03:35

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)